ConditionalsΒΆ

Java statements normally execute one at a time from top to bottom. If you want a statement to only execute when something is true use a conditional. Something that can only be true or false is called a Boolean. A conditional uses the keyword if followed by Boolean expression inside of an open parenthesis ( and a close parenthesis ) and then followed by a statement or block of statements. A block of statements is enclosed by an open curly brace { and a close curly brace }.

Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI).

if (isRaining) System.out.println("Take an umbrella!");
System.out.println("Drive carefully.");

The variable isRaining is a boolean variable that is either true or false. If it is true then the message Take an umbrella! will be printed and then execution will continue with the next statement which will print Drive carefully.. If it is false, execution continues with the next statement which will print Drive carefully..

What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might do one thing if a coin flip is heads and another if it is tails. In this case use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements.

if (isHeads) System.out.println("Let's go to the game.");
else System.out.println("Let's watch a movie.");

If isHeads is true it will print Let's go to the game., otherwise it will print Let's watch a movie..

You can even pick between 3 or more possibilites. Just add else if for each possibility after the first if and before the last possibility, the else.

if (x < 0) System.out.println("x is negative");
else if (x == 0) System.out.println("x is 0");
else System.out.println("x is positive");

Check your understanding

5-1-1: What does the following code print when x has been set to -5?

if (x < 0) System.out.println("x is negative");
else if (x == 0) System.out.println("x is zero");
else System.out.println("x is positive");




5-1-2: What does the following code print when x has been set to 2000?

if (x < 0) System.out.println("x is negative");
else if (x == 0) System.out.println("x is zero");
else System.out.println("x is positive");




5-1-3: What is the value of grade when the following code executes and score is 93?

if (score >= 90) grade = "A";
if (score >= 80) grade = "B";
if (score >= 70) grade = "C";
if (score >= 60) grade = "D";
else grade = "E";






5-1-4: Which of the following is equivalent to the code segment below?

if (x > 2) x = x * 2;
if (x > 4) x = 0;