Line At A Time
Lesson 12: Statements and Operators
Statements and Operators Mix &&, == and else if in one program.
1public static void main(String[] args) {
2 boolean isTrue = true;
3 int six = 6;
4 if (isTrue && six == 5) {
5 System.out.println("isTrue, six = 5");
6 } else if (isTrue) {
7 System.out.println("isTrue is true");
8 } else {
9 System.out.println("None of the above");
10 }
11}
Terminal
$ javac Main.java
$ java Main
isTrue is true
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 isTrue = true;
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.
int six = 6;
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 (isTrue && six == 5) {
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. Java checks six == 5 first (false, six is 6), then true && false, which is false, so this block is skipped.
System.out.println("isTrue, six = 5");
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.
} else if (isTrue) {
} 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. isTrue is true, so this block runs.
System.out.println("isTrue 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 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.
System.out.println("None of the above");
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: a branch 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 }.