Free Java Tutorials >> Table of contents >> If Statements

1. If statements, Else, Else If

If statements

First example

If statements are best introduced by example:

public class MyProgram {
    public static void main(String[] args) {
		int speedMph = 150;
		if( speedMph > 55 ) {
			System.out.println("You are speeding");
		}
		//An if statement is of the form
		//if(BOOLEAN) {
		//   //code that runs if BOOLEAN is true
		//}
    }
}

In the previous example, if speedMph is greater than 55, then the program will output "You are speeding", and otherwise it will output nothing

Specifically, an if statement is of the form if(CONDITION){ STATEMENTS }. If the condition, which must be a boolean, is true, then the statements are run.

If else

The previous if statement can be extended to include an "else" clause, which will run when the condition is false:

public class MyProgram {
    public static void main(String[] args) {
		int speedMph = 150;
		if( speedMph > 55 ) {
			System.out.println("You are speeding");
		} else {
			System.out.println("The bear eats you");
		}
		//if(BOOLEAN){ STATEMENTS } else { STATEMENTS }
    }
}

This else section is optional. It could be replaced by another if statement that checks the inverse of the condition, but an else is usually a more elegant solution.

If,else if,else if, else if,else

Rather than an else, we can also have else ifs after the first if. These will check secondary conditions. Only one of the possibilities ("branches") will be run. If no conditions are true then an else (assuming it exists) will be run:

public class MyProgram {
    public static void main(String[] args) {
		int speedMph = 150;
		if( speedMph > 55 ) {
			System.out.println("You are speeding");
		} else if( speedMph < 0) {
			System.out.println("Are you going faster than the speed of light?!");
		} else if( speedMph > 30 ) {
			System.out.println("Good job citizen");
		} else {
			System.out.println("The bear eats you");
		}
    }
}

If this first if statement is true, then it will output "You are speeding" and end the if statement. Otherwise, the if statement will check whether speedMph is less than 0, possibly ending there. We can have an arbitrarily large number of branches (hundreds of else ifs is possible).

A note about scope

If you create a variable within an if statement's curly brackets, it ceases to exist after the close curly. In fact, this will apply to many things in Java that use curly brackets:

public class MyProgram {
    public static void main(String[] args) {
		if(true) {
			int abc = 42;
			System.out.println(abc); //This compiles
		}
		System.out.println(abc); //This is an error
		//We can no longer use abc here, since the "scope" around abc has ended. 
		//If we wanted to use abc here, we should have declared it above the if statement
    }
}

We will discuss scope more in a later section.

Inline If statement

In Java, you can omit the curly brackets for an if statement when there is only one statement:

public class MyProgram {
    public static void main(String[] args) {
		if(5 > 3) {
			System.out.println("Example 1 is true");
		}
		if(5 > 3) System.out.println("This will also run");
    }
}

Note the lack of curly brackets in the second if. You can even put a new line between the close parenthesis and the println. However be very careful when dropping curly brackets. This is a common error:

public class MyProgram {
    public static void main(String[] args) {
		int d = 0;
		if( d == 5 ) 
			System.out.println("This will never run if d is 0"); 
			System.out.println("This will always run even though it is indented");
    }
}

Because Java ignores whitespace, this is the same as:

public class MyProgram {
    public static void main(String[] args) {
		int d = 0;
		if( d == 5 ) {
			System.out.println("This will never run if d is 0");
		}
		System.out.println("This will always run even though it is indented");
    }
}

2. Switch+Break and the ternary operator

Switch Statements

An alternative to the if statement is a switch statement. Although the syntax is different, the resulting logic is very similar. Here's an example:

public class MyProgram {
    public static void main(String[] args) {
        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

A switch statement will a different case based off the value of a variable. Thus, the previous switch has statements similar to if(month == 1) { monthString = "January"; }. The default case is run if none of the prior cases match.

At the end of each case, you need a break; keyword. Otherwise, the code will continue running. For example:

public class MyProgram {
    public static void main(String[] args) {
        int month = 3;
        switch (month) {
            case 1:  System.out.println("January");
            case 2:  System.out.println("February");
            case 3:  System.out.println("March");
            case 4:  System.out.println("April");
        }
    }
}

Notice that this program outputs both March and April. Without a break, the switch jumps to case 3 and executes every case after it as well.

The ternary operator

The ternary operator is an expression, unlike statements like if and switch. Here is an example:

public class MyProgram {
    public static void main(String[] args) {
        int month = 3;
        System.out.println(month <= 6 ? "spring" : "fall");
    }
}

This program prints "spring". The ternary operator has the syntax BOOLEAN ? VAL1 : VAL2. If BOOLEAN is true, then the expression equals VAL1. Otherwise, it equals VAL2. So for example, you could do this:

public class MyProgram {
    public static void main(String[] args) {
        int month = 3;
		int cost = 2 * (month <= 6 ? 2 : 3);
        System.out.println(cost);
    }
}

If month is less than 6, then cost equals 2*2. Otherwise, cost equals 2*3. Be careful using ternary operators, because they can make code more confusing.

3. Ordering variables using if statements

A common algorithm: sorting two variables

To sort two variables first and second in increasing order, swap them if they are out of order:

public class MyProgram {
    public static void main(String[] args) {
        int first = 5;
		int second = 0;
		if( first > second ) { //if they are out of order
			int tmp = first;      //swap them
			first = second;  
			second = tmp;    
		}
		System.out.println(first);  //0
		System.out.println(second); //5
    }
}

A common algorithm: finding the smallest of two variables

Minimization can be done with an if statement:

public class MyProgram {
    public static void main(String[] args) {
        int first = 5;
		int second = 2;
		int smallest = 0;
		if( first < second ) smallest = first;
		else smallest = second;
		System.out.println(smallest);  //2
    }
}

Note here that we in-lined the else as well, which is the same as:

public class MyProgram {
    public static void main(String[] args) {
        int first = 5;
		int second = 2;
		int smallest = 0;
		if( first < second ) {
			smallest = first;
		} else {
			smallest = second;
		}
		System.out.println(smallest);  //2
    }
}

A common algorithm: finding the largest of three variables

Maximization among three variables requires three if statements:

public class MyProgram {
    public static void main(String[] args) {
        int first = 5;
		int second = 0;
		int third = 3;
		int largest = 0;
		if( first > second && first > third ) largest = first;
		else if( second > first && second > third ) largest = second;
		else if( third > first && third > second ) largest = third;
		System.out.println(largest);  //5
    }
}

It may become clear now that we will need a more sophisticated programming technique to maximize or minimize many variables. We will revisit minimization and maximization when we learn about for loops and arrays

Previous: Booleans

Next: Boolean Logic