One-Way Selection with if
A one-way
if statement runs a group of statements only when a Boolean expression is true. The examples come from a music player that checks its volume level, from 0 to 100.The if statement
int volume = 65;
if (volume > 80)
{
System.out.println("Volume is high");
}
System.out.println("Playing");
The expression
volume > 80 is false, since 65 isn't greater than 80. The statement inside the braces is skipped, and Playing is the one line printed. With int volume = 90; on the first line the expression is true. Then both lines are printed, Volume is high first.Code after the body
A false Boolean expression skips the body and nothing more. In the run with volume 65,
Playing still printed. The program didn't stop, and the statements after the if ran as usual. A common misreading takes a false condition as the end of the program.A change made inside the body stays after the body ends.
int volume = 95;
if (volume > 80)
{
volume = 80;
}
System.out.println(volume);
Since 95 is greater than 80, the body runs and stores 80 in
volume. The last line prints 80. The assignment inside the braces is an ordinary assignment, and its value is there for every statement that follows. With a starting volume of 65 the body is skipped, no assignment happens, and the segment prints 65. Either way the volume printed is at most 80.The condition
Any expression whose value is
true or false can be the condition. A relational expression like volume > 80 is one kind. A boolean variable on its own is another.boolean muted = true;
if (muted)
{
System.out.println("Sound is off");
}
Here
muted already holds true, so it's a complete Boolean expression with nothing added. A call to a method that returns a boolean, such as equals, can stand in the same place.Braces
Braces group statements into a block, and every statement in the block is the body.
if (volume > 80)
{
System.out.println("Volume is high");
volume = 80;
}
Both statements run when the expression is
true, and neither runs when it's false.Java also accepts an
if with no braces. Then the body is the single statement right after the header, whatever the indentation shows. In the segment below, only the println belongs to the if, and the assignment runs every time, whatever the volume.if (volume > 80)
System.out.println("Volume is high");
volume = 80;
Writing the braces around every body, even a body of one statement, keeps the code meaning what its indentation shows.