if-else
The if-else statement is probably the most basic way to control program flow. The else is optional, so you can use if in two forms:
if(Boolean-expression)
statement
or
if(Boolean-expression)
statement
else
statement
The conditional must produce a boolean result. The statement is either a simple statement terminated by a semicolon, or a compound statement, which is a group of simple statements enclosed in braces. Any time the word “statement” is used, it always implies that the statement can be simple or compound.
As an example of if-else, here is a test( ) method that will tell you whether a guess is above, below, or equivalent to a target number:
//: c03:IfElse.java
import com.bruceeckel.simpletest.*;
public class IfElse {
static Test monitor = new Test();
static int test(int testval, int target) {
int result = 0;
if(testval > target)
result = +1;
else if(testval < target)
result = -1;
else
result = 0; // Match
return result;
}
public static void main(String[] args) {
System.out.println(test(10, 5));
System.out.println(test(5, 10));
System.out.println(test(5, 5));
monitor.expect(new String[] {
"1",
"-1",
"0"
});
}
} ///:~
It is conventional to indent the body of a control flow statement so the reader can easily determine where it begins and ends.