Line At A Time
Lesson 8: Else Statement
Else Statement Run one thing when true, another when false.
1public static void main(String[] args) {
2 boolean isFalse = false;
3 if (isFalse) {
4 System.out.println("isFalse is true");
5 } else {
6 System.out.println("isFalse is false");
7 }
8}
Terminal
$ javac Main.java
$ java Main
isFalse is false
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.
boolean isFalse = false;
boolean declares a variable that can store only one of two values: true or false. Watch the spelling: in Java the type is boolean; writing bool (like some other languages use) will not compile.
if (isFalse) {
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. Here the condition is false, so the code inside this block is skipped.
System.out.println("isFalse is true");
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 never runs, because the condition above is false.
} 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.
System.out.println("isFalse is false");
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 is the line that runs, because the if condition was false.
}
This } closes the else block.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.