if
As we saw in Java Control Flow Statements, making decisions in Java is accomplished by evaluating the state of program data using conditional operators such as ==, <, and >. if statements use the boolean value returned from these conditional expressions to determine whether the accompanying block of code should be executed. If the conditional expression returns true, the code block is executed. Otherwise, the code block is skipped.
Before we look at examples of the if statement, let's again take a look at their general form:
if(conditional_expression) {
statements_to_execute
}
This general form illustrates the simple if structure. If the conditional_expression is true, then statements_to_execute will be executed. The statements_to_execute are wrapped in curly braces {}. If statements_to_execute consists of a single statement only, the curly braces are optional. Most Java programmers consider it to be good coding style to always include the curly braces.
Let's look at some examples of if:
//Example 1
if(a == b) {
c++;
}
//Example 2
if((x <= y) && (y <= z)) {
System.out.println("Of course:\n");
System.out.println("x is less than or equal to z");
}
//Example 3
if(true) {
System.out.println("This line always executes");
}
//Example 4
if(!(employee.isManager())) {
System.out.println("Employee is not a manager.");
}
What if you want to execute one block of code when an expression evaluates to true but execute a different block of code when the same expression evaluates to false? The if statement alone is not enough because it only controls a single block of code. There are two ways to accomplish this. The first way is to use two if statements with mutually exclusive conditional expressions. The second way is to use an if-else structure. else is always used in conjunction with, and following, an if statement. else is the Java keyword designed for those situations where you must run exactly one of two code blocks.
Lets look at some examples of if-else:
//Example 1
if(a == b) {
c++;
}
if(a != b) {
c--;
}
//Example 2
if(a == b) {
c++;
}
else {
c--;
}
if-else structures can be followed by more if-else structures. This creates a control structure known as an if-else-if. The if-else-if structures can continue indefinitely, but many if-else-ifs strung together is usually a sign of a weak design. What differentiates a set of if statements from a set of if-else-if statements is that with the if-else-if statements, only one of the code blocks will be executed.
Lets look at some examples of if-else-if:
//Example 1
if(color == BLUE)) {
System.out.println("The color is blue.");
}
else if(color == GREEN) {
System.out.println("The color is green.");
}
//Example 2
if(employee.isManager()) {
System.out.println("Is a Manager");
}
else if(employee.isVicePresident()) {
System.out.println("Is a Vice-President");
}
else {
System.out.println("Is a Worker");
}