The if statement is a fundamental programming contruct. If allows a program to execute different blocks of code, depending on the result of a test. This tech-recipe describes the variations of the if statement in Java.
The general form of a Java if statement is as follows:
if (statement) {
code_block_true;
} else {
code_block_false;
}
where statement is anything that evaluates as a boolean value. If the statement is true, then the Java code in the “code_block_true” block is executed. Otherwise, the code in “code_block_false” is executed. The else statement is optional, so the simplest example of the if statement is the following:
if ( x == 1 ) {
System.out.println("yep, x is one.");
}
A block of code is either a single line of code or several lines of code contained in curly braces. Note that, in this example, enclosing the code in curly braces is not required. However, some programmers prefer to use them anyway since it makes it clearer what code is exectued.
Multiple else if conditions can be chained together as follows:
if ( x == 1 )
System.out.println("one");
else if ( x > 1 ) {
y = x*2;
System.out.println("many");
} else {
y = -x;
System.out.println("negative");
}