So far the behaviour of our programs has been pretty predictable, the same statements have been run in sequence every time we execute our code. To write more dynamic programs we need to be able to check conditions and react accordingly. In Java, selection is accomplished with a control structure called an if statement. Below we’ll cover several variations of it.
Here is a simple example of an if statement in action:
1 2 3 |
if ( num > 0 ) { System.out.println( num + " is positive." ); } |
The keyword if is followed by a conditional expression (the result will be either true or false). The parentheses ( .. ) around the condition are required syntax. The code between curly braces { .. } defines the block of code that will execute only if the condition evaluates to true. Also, note that the code block is indented 4 spaces for optimal readability.
If the block of code contains only one statement, then the curly braces { .. } are syntactically optional, but you should still indent the statement. For example, this code produces the same result:
1 2 |
if ( num > 0 ) System.out.println( num + " is positive." ); |
Professionals and a lot of books tend to follow this form, but I’d recommend (especially when learning) to keep using the braces { .. } for consistency and understandability. If you follow my advice you will avoid silly logic errors like this:
1 2 |
if ( num > 0 ); System.out.println( num + " is positive." ); |
Can you spot the problem? I’ve “accidentally” put a semicolon (;) at the end of the first line after the condition. This code will compile but will always print that num is positive no matter what the result of the if condition is. Adding a semi-colon to the end of each Java statement becomes second nature. If you don’t type an opening curly brace { you may accidentally type a semi-colon instead.
Alternatively, you might decide later to add more statements to execute if the condition is true:
1 2 3 |
if ( num > 0 ) System.out.print( num ); System.out.println( " is positive." ); |
The problem here is that the second output statement is not associated with the if statement at all, even though the indentation suggests that it is. The code above will always display “is positive.” whether the if condition is true or false. Be careful!
The if..else Statement
Sometimes we want to evaluate one block of code if a condition is true, and a different block of code if a condition is false. To do this we use an if..else statement.
1 2 3 4 5 6 |
if ( num > 0 ) { System.out.println( num + " is positive." ); } else { // else clause is optional System.out.println( num + " is zero or negative" ); } |
If you think about this, the if..else statement follows similar logic to the ?: operator. The ?: operator is only useful in simple situations and can quickly become unreadable. For this reason, I would recommend using the if..else instead.
The if..else if..else Statement
And, sometimes we want to evaluate a series of conditions. In Java, we use the if..else if..else statement to do this.
1 2 3 4 5 6 7 8 9 |
if ( num > 0 ) { System.out.println( num + " is positive." ); } else if (num < 0 ) { // You can have many else if clauses System.out.println( num + " is negative." ); } else { // else is optional System.out.println( num + " is zero." ); } |
You can have as many else if clauses as you need, and the else clause is optional – you can leave it out. Java evaluates if..else if conditions in sequence from the top down. Once a condition evaluates to true, Java does not evaluate the rest of the if..else if conditions. Because of this, it’s more efficient to put the most likely conditions first and the least likely ones last.
The Dangling-else Problem
Notice in the examples above that each block of code is enclosed in curly braces { .. } and indented 4 spaces for maximum readability. As mentioned earlier, if there is only one line of code associated with a condition the curly braces are optional. But again this can lead to logic errors! Consider the following example:
1 2 3 4 5 |
if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are greater than 5" ); else System.out.println( "x is <= 5" ); |
The question here is which if is the else associated with? This ambiguity is famously known as the “Dangling-else Problem”. It turns out that the Java compiler automatically associates an else with the immediately preceding if unless you override this with curly braces { .. }.
In the example above, the else is associated with the inner if (where y is being compared) rather than the outer if (where x is compared). Let’s fix this logic error:
1 2 3 4 5 6 |
if ( x > 5 ) { if ( y > 5 ) System.out.println( "x and y are greater than 5" ); } else System.out.println( "x is <= 5" ); |
If you always include curly braces { .. } you can avoid this kind of logic error in the first place. Even the Dr Java IDE gets confused if you don’t include braces and re-indent your code.
You Try!
-
- Revise Q2, 3, & 4 from 1-6 using an if or if..else statement instead of the ?: operator.
- There is a statement called switch that can be used in place of an if..else if..else statement. Research the switch statement and convert the if..else if..else statement in the code below to a switch statement.
1234567891011121314151617181920212223242526import java.util.Scanner;public class ConvertSwitch {public static void main( String[] args ){Scanner input = new Scanner( System.in );int choice;System.out.print("Please enter your choice (1, 2, 3, or 4):");choice = input.nextInt();if (choice == 1) {System.out.println("You selected 1.");}else if (choice == 2 || choice == 3) {System.out.println("You selected 2 or 3");}else if (choice == 4) {System.out.println("You selected 4.");}else {System.out.println("Invalid Selection!");}}}