Two-Way Selection with else
The else clause
A one-way
if runs its body or does nothing. Often a program has to do one thing or another. Java writes that with an else clause. The music player now reports on every volume level.int volume = 65;
if (volume > 80)
{
System.out.println("Too loud");
}
else
{
System.out.println("Volume OK");
}
Since 65 isn't greater than 80,
volume > 80 is false. The if body is skipped and the else body runs, printing Volume OK. With a volume of 90 the expression is true, and the segment prints Too loud instead.The end of the statement
An
if with an else is one statement. It ends with the else body's closing brace, and whatever follows runs no matter which body ran.if (volume > 80)
{
System.out.println("Too loud");
}
else
{
System.out.println("Volume OK");
}
System.out.println("Next song");
With a volume of 65 the segment prints
Volume OK and then Next song. With 90 it prints Too loud and then Next song.The
else has no Boolean expression of its own. It follows the if body's closing brace directly, with no statement between them. A statement placed there would end the if, leaving the else unattached, and the code wouldn't compile.Opposite conditions
The same choice can be written as two one-way
if statements, one after the other. For that to work, the second condition must be false wherever the first is true, and true wherever it's false. The first body also must not change what the second condition reads, which the last section shows.The opposite of
volume > 80 is volume <= 80. The values on either side of 80 show why it can't be volume < 80.volume volume > 80 volume < 80
79 false true
80 false false
81 true false
At 80,
volume <= 80 is true, but both volume > 80 and volume < 80 are false, so a pair built from them runs neither body for that one value. It works for every other volume, which is how the mistake survives a quick test.Two separate ifs
Two
if statements are evaluated one after the other, and the second condition is evaluated after the first body has run. The first body may change a variable that the second condition reads. Then the pair can behave differently from an if with an else, even with the opposite condition.if (volume > 80)
{
volume = 80;
System.out.println("Lowered to 80");
}
if (volume <= 80)
{
System.out.println("Volume OK");
}
Start at 95. The first body runs and sets
volume to 80. The second condition is then evaluated with 80, so it's true, and the segment prints both lines. Written with else, the expression is evaluated a single time, at 95, and only Lowered to 80 is printed.