if, else and ?:
In the previous lesson the program answered the signpost's questions: true or false. Now it is time to turn by the answer. At a fork you take one road, and this time you do not take the other.
A program needs the same thing: run one piece of code and skip another. The statements in main run in order, from top to bottom. An if statement runs a block of code only when its condition is true, and the block after else runs when it is false:
public class Main {
public static void main(String[] args) {
int t = 25;
if (t < 0) {
System.out.println("frost");
} else if (t < 20) {
System.out.println("cool");
} else {
System.out.println("warm"); // warm
}
}
}Let's walk through the program:
int t = 25;: it is 25 degrees outside.if (t < 0): the condition is false, so the program skips the first block.else if (t < 20): this condition is false too.else: the last block is all that is left, and the program printswarm.
Three kinds of branches
A block in braces that runs under its own condition is called a branch. The example has three, and each has its own role.
if
The if branch opens the fork. Its header has three parts:
- the keyword
if; - a condition in parentheses, such as
(t < 0); - a block in braces that runs when the condition is true.
The parentheses around the condition are required: without them the compiler answers '(' expected. The condition itself has type boolean, so if (t) with a number t does not compile. An if can also stand alone, with no else: then nothing runs when the condition is false.
else if
An else if branch adds one more condition to the fork. It is checked only when every condition above it turned out false.
The chain is checked from top to bottom. The first branch with a true condition runs, and the rest are skipped. That is why the second branch needs only t < 20: it is already known that t is not below zero.
Here the fork differs from Java. A traveler can look over all the signposts and pick the best one. Java reads them strictly from top to bottom and turns at the first one whose answer is true.
else
The else branch has no condition. It runs when every condition above it is false, and it always comes last. Without it, nothing runs in that case.
Braces
Braces gather several statements into one branch. Without braces only one statement belongs to the branch: the first one after the condition. Java does not read indentation: an indented line without braces is not part of the branch. That is why a branch always goes in braces, even when it is one line.
The conditional operator ?:
Sometimes the branches differ only in a value: the weather is warm or cool. For that choice there is the conditional operator ?:. It does not perform actions; it produces a value itself:
int t = 25;
String word = t < 20 ? "cool" : "warm";
System.out.println(word); // warmt < 20 ? "cool" : "warm" has three parts:
- the condition
t < 20; - after
?, the value for when the condition is true:"cool"; - after
:, the value for when the condition is false:"warm".
The condition is false, so word gets "warm". The operator has three parts, which is why it is also called the ternary operator. Both values must fit the variable: here they are strings. When there are three or more options, use if and else if rather than a chain of several ?:.
Common mistake
The second line of a branch was indented but not put in braces:
int balance = 500;
if (balance < 100)
System.out.println("low balance");
System.out.println("top up your card"); // ✗The program prints top up your card, although there is enough money. The indentation lies: only the first statement belongs to the if. The second stands outside the if and always runs. Put both lines in braces, and with a balance of 500 nothing is printed. Interviewers like to show this trap.
Key points
ifruns its branch when the condition is true, andelsewhen every condition above is false.- An
else ifchain runs the first branch with a true condition and skips the rest. - Without braces a branch owns one statement, so braces always go in.
ok ? a : bgivesawhen the conditionokis true, andbwhen it is false.