Skip to main content
Logo image

Section 2.4 Nested if Statements

90 minutes
If statements can be nested inside other if statements. Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements. The Boolean expression of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
if (boolean expression)
{   // This nested if is executed if outer if is true
    if (boolean expression)
    {
        statement;
    }
}

Subsection 2.4.1 Multiway selection (else if)

A single if/else statement allows us to select between 2 branches of code. With nested if/else statements, we can pick between 3 or more branches of code. 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.
Just add else if for each possibility after the first if, and else before the last possibility like below.
// 3 way choice with else if
if (boolean expression)
{
   statement1;
}
else if (boolean expression)
{
   statement2;
}
else
{
   statement3;
}

Activity 2.4.1.

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 2.4.1. The order that statements execute in a conditional with 3 options: if, else if, and else

Activity 2.4.2.

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 2.4.3.

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 2.4.4.

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 2.4.5.

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 2.4.6.

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 2.4.2 Dangling Else Statements

Sometimes with nested ifs we find a dangling else that could potentially belong to either if statement. The rule is that the else clause will always be a part of the closest unmatched if statement in the same block of code, regardless of indentation.
// Nested if with dangling else
if (boolean expression)
   if (boolean expression)
      Do statement;
   else  // belongs to closest if
      Do other statement;

Activity 2.4.7.

Try the following code with a dangling else. Notice that the indentation does not matter to the compiler (but you should make it your habit to use good indentation just as a best practice). How could you get the else to belong to the first if statement?
You can use curly braces ({}) to enclose a nested if and have the else clause belong to the top level if clause like below:
// Nested if with dangling else
if (boolean expression)
{
   if (boolean expression)
      Do this statement;
}
else  // belongs to first if
  Do that statement;
In fact many experienced Java programmers always use curly braces, even when they are not technically required to avoid this kind of confusion.

Subsection 2.4.3 Coding Challenge : Adventure

One of the first games coded for early computers in the 1970s was called Colossal Cave Adventure
 2 
https://en.wikipedia.org/wiki/Colossal_Cave_Adventure
. It was a text-based interactive fiction game where you had to make your way through an elaborate cave. The program only understood one word or phrase commands like north, south, enter, take, etc. You can try playing adventure
 3 
http://www.web-adventures.org/cgi-bin/webfrotz?s=Adventure
recreated online following some of the commands in this walkthrough
 4 
https://adventuregamers.com/walkthrough/full/colossal-cave
. Part of the challenge is finding the commands that the code will understand.
In a game like Adventure, else if statements can be used to respond to commands from the user like n, s, e, w. Try the program below (or in an interactive input IDE like JuiceMind
 5 
https://play.juicemind.com/dashboard/teams/Mk2wWMTqPkekcxTDWqRn/item/54bfe3f4-f112-4062-8d7d-a033b2bf09b6#079f4341-137a-497f-b874-553ababd627a
or replit
 6 
https://replit.com/@BerylHoffman/Adventure#Main.java
). This current adventure game asks the user whether they want to move n, s, e, or w, but right now only the north direction is coded. It leads to a new method called forest().
In the main method, add in else if statements to go in the directions of β€œs” for south, β€œe” for east, β€œw” for west, and an else statement that says β€œYou can’t go in that direction”. Be creative and come up with different locations in each direction. Have each direction call a static method that you will write. The forest() and sea() methods are shown as examples for two of the diretions. You will need to change the input below the code to s or e or w and then run to test these branches. How many test-cases are needed to test all branches of your code? You can also connect locations to one another by calling their methods. If you have time, you can expand this game further with more nested if/else statements and come up with a different adventure location.

Project 2.4.8.

This is a text adventure game that lets the user move in 4 different directions. Right now, it only lets the user move north. Add in else if statements to go in the directions of "s" for south, "e" for east, "w" for west, and an else statement that says "You can’t go in that direction". Be creative and come up with different locations in static methods below main for each direction. There are 5 TODO steps below.

Subsection 2.4.4 Summary

  • (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.
// 3 way choice with else if
if (boolean expression)
{
   statement1;
}
else if (boolean expression)
{
   statement2;
}
else
{
    statement3;
}

Subsection 2.4.5 AP Practice

Activity 2.4.9.

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.