Line At A Time
Lesson 9: Else If Statement
Else If Statement Check several conditions, one after another.
1public static void main(String[] args) {
2 int two = 2;
3 if (two == 1) {
4 System.out.println("Two = 1");
5 } else if (two == 2) {
6 System.out.println("Two = 2");
7 } else {
8 System.out.println("Two != 1 or 2");
9 }
10}
Terminal
$ javac Main.java
$ java Main
Two = 2
Every line, explained
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
int two = 2;
int declares a variable that stores a whole number (an "integer") like 1, 5 or 1000. The = sign stores the value on the right into the variable named on the left, and the semicolon ; ends the statement, like a full stop at the end of a sentence.
if (two == 1) {
if checks the condition inside its parentheses. If the condition is true, Java runs the code between the { and }. If it is false, Java skips that code completely. == compares two values and asks "are these equal?". Be careful: a single = stores a value, a double == compares. Here 2 == 1 is false, so this block is skipped.
System.out.println("Two = 1");
System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". Skipped: two is not 1.
} else if (two == 2) {
} else if (...) { adds another check that is only tried when the condition above it was false. Java tests each condition from top to bottom and runs the first block whose condition is true, skipping all the rest. Here 2 == 2 is true, so this block runs.
System.out.println("Two = 2");
System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". This line runs.
} else {
} else { attaches an "otherwise" branch to the if above. When the if condition is false, the code inside the else block runs instead. Exactly one of the two blocks runs, never both. This else only runs when every check above it failed.
System.out.println("Two != 1 or 2");
System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". Skipped: the else if above already matched.
}
This } closes the else block.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.