Skip to main content
Logo image

Section 4.2 Booleans and if statements

Since the definition of a selection is a point in the code where the flow of control makes a decision to go down one branch or another based on some value, we need a data type to represent those values. Some older languages just reuse an existing data type, such as their equivalent of int, treating 0 as false and all other numbers as true. And some modern languages, in an attempt to be more lenient will treat any value at all as a true or false value, following some oftentimes complicated rules about what values are β€œtruthy” and what values are β€œfalsey”.
In Java, however, things are quite tidy with true and false represented by a special data type, the third primitive data type you need to know for the AP exam, boolean. The data type is named for George Boole, a 19th century English mathematician who invented Boolean algebra, a system for dealing with statements made up of only true and false values.
A boolean variable or expression can only have one of two values, true or false. There are two literals values we can use in Java to get these values: true and false. So we can declare boolean variables like this:
boolean hungry = true;
boolean sleepy = false;
And that’s kind of it for boolean as a data type. Unlike int and double there aren’t any gotchas about how they differ from idealized numbers in mathematics. And there aren’t complexities about different ways to write the same value.
However there are a lot of ways we can produce boolean values. There are operators the operate on booleans to produce new boolean values, which allow us to express complex conditions. There are operators that operate on other kinds of values to produce boolean values, like the > operator that compares two numbers, producing true if the first number is greater than the second and false otherwise.
But before we look at all the different ways of producing boolean values, let look at how they are used in Java’s most basic selection control constructs, if statements.

Subsection 4.2.1 One-way selection

Almost all programming languages have something like an if statement to choose between different paths in an algorithm. An if statement is one of the simplest forms of the selection construct that we need as one of our three algorithmic building blocks. The simplest form of an if statement in Java looks like:
if (someBoolean) {
  someCode();
  maybeSomeMoreCode();
}
The expression in the parentheses must be a boolean expression: a boolean literal (though that would be silly for reasons we’ll discuss in a bit), a boolean variable, or some other expression that evaluates to a boolean.
And the code in {}s is called the body of the if statement and contains the code to run if the boolean expression is true. It can contain any number of statements including, as we’ll see other if statements and loops.
This form of if statement is called a one-way selection because it makes one choice and then either executes the body or does nothing. In either case, the normal flow of control picks up after the if statement, continuing with whatever code comes next.
Figure 4.2.1. Flowchart of a one-way selection
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) or Ubiquitous Computing (computers are everywhere).

Activity 4.2.1. Take an umbrella?

In the code below, the boolean variable isRaining is used to control whether the message Take an umbrella! will be printed. Regardless of whether isRaining is true or false, then execution will continue with the next statement which will print Drive carefully. Run the code below to see this.

Activity 4.2.2. Change isRaining.

Subsection 4.2.2 Two-way selection

What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might flip a coin and do one thing if it lands as heads and another if it is tails. In programming, you can 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.
// A block if/else statement
if (boolean expression) {
   statement1;
   statement2;
} else {
   do other statement;
   and another one;
}
// A single if/else statement
if (boolean expression)
  Do statement;
else
  Do other statement;
A two-way selection (if-else statement) is used when there are two segments of codeβ€”one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.
The following flowchart demonstrates that if the condition (the boolean expression) is true, one block of statements is executed, but if the condition is false, a different block of statements inside the else clause is executed.
Figure 4.2.2. Flowchart of a two-way selection

Activity 4.2.3.

Try the following code. If isHeads is true it will print Let's go to the game and then after conditional.

Activity 4.2.4.

Subsection 4.2.3 Multiway selection

Since the body of an if statement or an else can contain any code, we can nest if statements inside other if statements. There’s nothing magical about this: just the natural consequence of building programs out of simple pieces. Consider this code:
if (hungry) {
  if (sleepy) {
    eatQuickSnack();
  } else {
    makeSomethingFancy();
  }
}
The outer if is a one-way selection that will run some code if hungry is true. The body of that if statement is another if statement that implements a two-selection based on the value of sleepy. So really this code is choosing between three outcomes, one when hungry and sleepy are both true, one when hungry is true but sleepy is false, and one when hungry is false. In the latter case the code doesn’t do anything.
Now look at another if, this time with another if nested in the body of the else.
if (hungry) {
  eatSnack();
} else {
  if (sleepy) {
    takeNap();
  } else {
    doHomework();
  }
}
This code also chooses between three outcomes but in each of the outcomes some code runs: eatSnack() if hungry is true, takeNap() if sleepy is true, and doHomework() otherwise.
To emphasize that the three branches are all kind of at the same level we’d normally format this code slightly differently:
if (hungry) {
  eatSnack();
} else if (sleepy) {
  takeNap();
} else {
  doHomework();
}
When we chain together if statements like this, it is called a multiway selection because the code chooses not between running code or not as in a one-way selection, or between two pieces of code as in a two-way selection, but between as many different pieces of code as we want to chain together.

Activity 4.2.5.

Run the code below and try changing the value of x to get each of the three possible lines in the conditional to print.
Here is a flowchart for a conditional with 3 options like in the code above.
Figure 4.2.3. Flowchart of a three-way selection

Note 4.2.4.

Another way to handle 3 or more conditional cases is to use a switch statement but that is outside the AP curriculum. For a tutorial on using switch see The switch Statement tutorial on Oracle’s website.

Activity 4.2.6.

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");
}
  • x is negative
  • When x is equal to -5 the condition of x < 0 is true.
  • x is zero
  • This will only print if x has been set to 0. Has it?
  • x is positive
  • This will only print if x is greater than zero. Is it?

Activity 4.2.7.

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");
}
  • x is negative
  • This will only print if x has been set to a number less than zero. Has it?
  • x is zero
  • This will only print if x has been set to 0. Has it?
  • x is positive
  • The first condition is false and x is not equal to zero so the else will execute.

Activity 4.2.8.

What does the following code print when x has been set to .8?
if (x < .25)
{
    System.out.println("first quartile");
}
else if (x < .5)
{
    System.out.println("second quartile");
}
else if (x < .75)
{
    System.out.println("third quartile");
}
else
{
    System.out.println("fourth quartile");
}
  • first quartile
  • This will only print if x is less than 0.25.
  • second quartile
  • This will only print if x is greater than or equal to 0.25 and less than 0.5.
  • third quartile
  • The first only print if x is greater than or equal to 0.5 and less than 0.75.
  • fourth quartile
  • This will print whenever x is greater than or equal to 0.75.

Activity 4.2.9.

The else-if connection is necessary if you want to hook up conditionals together. In the following code, there are 4 separate if statements instead of the if-else-if pattern. Will this code print out the correct grade? First, trace through the code to see why it prints out the incorrect grade. Use the Code Lens button. Then, fix the code by adding in 3 else’s to connect the if statements and see if it works.

Activity 4.2.10.

Finish the following code so that it prints β€œPlug in your phone!” if the battery is below 50, β€œUnplug your phone!” if it is at or above 100, and β€œAll okay!” otherwise. Change the battery value to test all 3 conditions.

Subsection 4.2.4 Coding Challenge: Magic 8 Ball

Magic 8 Ball
Have you ever seen a Magic 8 ball? You ask it a yes-no question and then shake it to get a random response like Signs point to yes!, Very doubtful, etc. If you’ve never seen a Magic 8 ball, check out this simulator. In the exercise below, come up with 8 responses to yes-no questions. Write a program below that chooses a random number from 1 to 8 and then uses if statements to test the number and print out the associated random response from 1-8. If you need help with random numbers, see the Math lesson and remember the formula (int) (Math.random() * max) + min.

Project 4.2.11.

Complete the printRandomResponse() method to print out 1 of 8 random responses and the lucky() method to toss a coin and print out β€œLucky!” or β€œNo Luck!” based on the result. Run the code multiple times to see the responses.
You can make this code more interactive by using the Scanner class to have the user ask a question first; you can try your code with input in JuiceMind or replit or a local IDE.

Subsection 4.2.5 Summary

  • (AP 2.3.A.1) Selection statements change the sequential execution of statements.
  • (AP 2.3.A.2) An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
  • (AP 2.3.A.3) A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
  • if statements test a boolean expression and if it is true, go on to execute the body which is the following statement or block of statements surrounded by curly braces ({}) like below.
  • (AP 2.4.A.1) Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements.
  • (AP 2.4.A.2) The Boolean expression of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
  • (AP 2.4.A.3) A multi-way selection (if-else-if) is used when there are a series of expressions with different segments of code for each condition. Multi-way selection is performed such that no more than one segment of code is executed based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.
// A single if statement
if (boolean expression)
    Do statement;
// A block if statement
if (boolean expression)
{
   Do Statement1;
   Do Statement2;
   ...
   Do StatementN;
}
  • Relational operators (==, !=, <, >, <=, >=) are used in boolean expressions to compare values and arithmetic expressions.
  • If statements can be followed by an associated else part to form a 2-way branch:
if (boolean expression)
{
    Do statement;
}
else
{
    Do other statement;
}
  • (AP 2.3.A.4) A two-way selection (if-else statement) is used when there are two segments of codeβ€”one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.

Subsection 4.2.6 AP Practice

Activity 4.2.12.

Consider the following code segment.
int speed = 35;
boolean rain = false;

if (rain)
{
   speed -= 10;
}

if (rain == false)
{
  speed += 5;
}

if (speed > 35)
{
   speed = speed - 2;
}

System.out.println(speed);
What is printed as a result of executing the code segment?
  • Some of the if statement conditions are false so they will not run.
  • Take a look at the changes to speed in the if statements.
  • Correct! The first if statement condition is false, and the second and third if conditions are true.
  • The first if statement would only run if rain is true.
  • The second if statement would run since rain is false.

Activity 4.2.13.

Consider the following code segment.
int x = 5;

if (x < 5)
{
   x = 3 * x;
}

if (x % 2 == 1)
{
   x = x / 2;
}

System.out.print(2*x + 1);
What is printed as a result of executing the code segment?
  • Take a look at the second if statement again!
  • Take a look at the second if statement again!
  • The first if statement condition is false.
  • The first if statement condition is false.
  • Correct! The first if statement is not true. The second one is true since 5 is odd, and x becomes 2. And 2*2 + 1 = 5 is printed out.

Activity 4.2.14.

Consider the following code segment where a range of β€œHigh”, β€œMiddle”, or β€œLow” is being determined where x is an int and a β€œHigh” is 80 and above, a β€œMiddle” is between 50 - 79, and β€œLow” is below 50.
if (x >= 80)
{
   System.out.println("High");
}

if (x >= 50)
{
  System.out.println("Middle");
}
else
{
   System.out.println("Low");
}
Which of the following initializations for x will demonstrate that the code segment will not work as intended?
  • This would print out both β€œHigh” and β€œMiddle”, showing that there is an error in the code. As you will see in the next lesson, one way to fix the code is to add another else in front of the second if.
  • This would correctly print out β€œMiddle”.
  • This would correctly print out β€œMiddle”.
  • This would print out β€œLow” which is correct according to this problem description.
  • This would print out β€œLow” which is correct according to this problem description.

Activity 4.2.15.

Assume an int variable x has been properly declared and initialized. Which of the following code segments will print out β€œHigh” if x is 66 and above, β€œMedium” is x is between 33-65, and β€œLow” if x is below 33.
I.   if (x > 66)
     {
       System.out.println("High");
     }
     else if (x > 33)
     {
       System.out.println("Medium");
     }
     else {
       System.out.println("Low");
     }

II.  if (x < 33)
     {
       System.out.println("Low");
     }
     else if (x < 66)
     {
       System.out.println("Medium");
     }
     else {
       System.out.println("High");
     }

III. if (x >= 66)
     {
       System.out.println("High");
     }
     if (x >= 33)
     {
       System.out.println("Medium");
     }
     if (x < 33)
     {
       System.out.println("Low");
     }
  • I only
  • If x = 66, it should print out β€œHigh”.
  • II only
  • Correct!
  • III only
  • If x is 66, the code in III. will print out more than one thing.
  • I and II only
  • If x = 66, it should print out β€œHigh”.
  • II and III only
  • If x is 66, the code in III. will print out more than one thing.
You have attempted of activities on this page.