Sub topic 4
Nest Decisions and Use Braces to Clarify Which else Belongs Where
A library checkout desk asks two questions. Do you have a library card? If so, is the book available? If you do not have a card, the desk does not need to ask the second question.
In Java, you can show that link by putting one if inside another. The hard part is not writing the second if. It is making clear which question each else answers. In this chapter, you will trace a checkout program, see how an else can answer the wrong question, and fix the problem with braces.
Put the second question inside the first
A condition is a test that gives true or false. A branch is a path the program can take based on that test. A block is a group of statements between an opening brace and a closing brace. A statement is an instruction for Java to carry out.
Nesting means putting one part of the code inside another. In a nested decision, the outer if controls whether Java enters a block. The inner if asks a second question inside that block. If Java skips the block, it skips the inner question as well.
In the checkout example, the outer condition checks for a card. The inner condition checks the book. The inner if goes inside the cardholder block because the book only matters to the checkout decision after the card check passes.
Run the checkout program
Save this example as Main.java and run it with your usual Java setup. Each later example is also a complete Main.java program. Replace the earlier example when you want to try the next one.
A boolean variable is a named place that holds either true or false. To try different checkout cases, you only need to change the two boolean values near the top.
public class Main {
public static void main(String[] args) {
boolean hasLibraryCard = true;
boolean bookAvailable = false;
if (hasLibraryCard) {
if (bookAvailable) {
System.out.println("You can check out the book.");
} else {
System.out.println("The book is not available.");
}
} else {
System.out.println("You need a library card.");
}
System.out.println("Check finished.");
}
}With the values shown, the program prints “The book is not available.” and then “Check finished.” The message about needing a card does not print. That message belongs to the outer else, and the outer condition was true. The book being unavailable does not change the result of the card check.
Trace all four pairs of values
To trace code is to follow what it does one step at a time. Start at the outer condition, not at the message you think will print. For each condition Java reaches, follow just the path for its result.
Try to predict the first line for each pair before you run it. The last two rows are worth testing separately. The book value changes, but the path does not.
| hasLibraryCard | bookAvailable | Does Java test bookAvailable in the inner if? | First line printed |
|---|---|---|---|
| true | true | Yes | You can check out the book. |
| true | false | Yes | The book is not available. |
| false | true | No | You need a library card. |
| false | false | No | You need a library card. |
In the third row, Java still sets bookAvailable to true at the start. What it skips is the condition that reads that value. Setting a value and testing it are two different steps.
“Check finished.” prints for every row. Its statement comes after both blocks of the outer decision. This is a useful way to read a nested example: first find what runs only on one path, then find where the paths come back together.
Find the if that owns each else
An else belongs to one if. To find out which one in braced code, look at the closing brace just before the else. Then find the opening brace it matches. In the checkout program, the first else follows the block opened by the book check. The second else follows the larger block opened by the card check.
Indentation is the space at the start of a line. Good indentation helps you see the blocks: the inner if and its else line up with each other, one level to the right of the outer if and its else. But Java does not use that spacing to choose which if owns an else.
When an else could seem to go with two different if statements, Java attaches it to the nearest if that can still take an else. In code with missing braces, this is often called the dangling else problem. Java knows what the code means. The problem is that a person reading it may expect a different meaning.
See how misleading spacing hides a bug
This version has a smaller goal. It should print a checkout message if the person has a card and the book is available. It should print a card reminder if the person has no card. If the person has a card but the book is unavailable, it should print only “Check finished.”
The code runs, but two of those cases are wrong. Look at the else before you try it. Which if does the spacing suggest it belongs to?
public class Main {
public static void main(String[] args) {
boolean hasLibraryCard = true;
boolean bookAvailable = false;
if (hasLibraryCard)
if (bookAvailable)
System.out.println("You can check out the book.");
else
System.out.println("You need a library card.");
System.out.println("Check finished.");
}
}The else lines up with the card check. Yet it belongs to the book check. There is no brace to end the cardholder block before the else. Java reads the whole inner if and else as the one statement controlled by the outer if.
With a card and an unavailable book, Java enters the outer if. Then the inner condition is false, so its else prints “You need a library card.” That is the wrong message for someone who has a card. Now set hasLibraryCard to false and run it again. Java skips the entire inner decision, including the reminder. You see only “Check finished.”
Close the outer if block before its else
The fix is to put the entire book check inside a braced cardholder block. Give the book check its own braces too. After that inner block closes, close the outer if block. Only then write the else for the card check.
public class Main {
public static void main(String[] args) {
boolean hasLibraryCard = true;
boolean bookAvailable = false;
if (hasLibraryCard) {
if (bookAvailable) {
System.out.println("You can check out the book.");
}
} else {
System.out.println("You need a library card.");
}
System.out.println("Check finished.");
}
}Look at the two closing braces before the reminder message. The first closes the block for bookAvailable. The next closes the block for hasLibraryCard and is followed by else. At that point, the inner if is already inside a finished block. The else cannot reach back into that block and attach to it.
Run this version with the values shown. It now prints only “Check finished.” The person has a card, so the reminder does not run. The book is unavailable, so checkout does not run either. That silence is on purpose for this version. Now change hasLibraryCard to false. You should get the reminder, followed by “Check finished.”
Test the cases that can tell the versions apart
If you only test with a card and an available book, both versions look right. They both print the checkout message and then finish. That run does not tell you whether the else is attached to the right if.
| Test case | Version without braces | Fixed version |
|---|---|---|
| Card present, book available | Prints the checkout message | Prints the checkout message |
| Card present, book unavailable | Prints the card reminder | Prints no checkout or reminder message |
| Card absent, book available | Prints no checkout or reminder message | Prints the card reminder |
Both versions still print “Check finished.” in every case. When you test your own nested code, try a false outer condition and a true outer condition with a false inner condition. Those two tests help you tell the outer else from the inner one.
Nest a decision inside an else block
A follow-up question can go inside either branch. Say the library changes the choices for cardholders. If the book is available, they can check it out. If it is not, the program first tells them the bad news. Only on that path does the program check whether the library allows a hold. A hold is a request to save the book for later.
The example starts after the card check. Here the outer question is now about book availability, and the inner question sits inside its else block.
public class Main {
public static void main(String[] args) {
boolean bookAvailable = false;
boolean holdsAllowed = true;
if (bookAvailable) {
System.out.println("You can check out the book.");
} else {
System.out.println("The book is not available.");
if (holdsAllowed) {
System.out.println("You can place a hold.");
} else {
System.out.println("Holds are not allowed for this book.");
}
}
}
}With these values, the program prints “The book is not available.” and then “You can place a hold.” Change holdsAllowed to false. The first line stays the same, but the second line changes. Now set bookAvailable to true. You get only the checkout message, no matter what value holdsAllowed has.
The placement of the unavailable message matters. It sits inside the outer else but outside the inner if and else. That means everyone on the unavailable path sees it, whether or not they can place a hold. If you put the message inside the holdsAllowed block, people who cannot place a hold would miss it.
Review a nested decision from the outside in
Before you write a nested decision, say when the follow-up question matters. For example: “Check the book only when there is a card,” or “Check whether holds are allowed only when the book is unavailable.” That sentence tells you which block should contain the inner if. If two checks should always happen, putting one inside the other would make Java skip a check you meant to run.
When the code is written, review it in this order:
- Find the outer condition. For each result, point to the block Java enters or say that it skips the decision.
- Find the inner condition. Name the outer path that reaches it and a path that skips it.
- For each else, match the brace just before it to its opening brace. Name the condition whose false result leads to that else.
- Check the position of any message that more than one path should print. If it belongs to every path through the whole decision, put it after the whole decision.
- Run cases that reach different paths. A result that looks right on the first run does not prove the other branches are right.
Practice tracing and fixing nested branches
Exercise
In the first checkout program, hasLibraryCard is false and bookAvailable is true. Which lines print, and does Java test bookAvailable in the inner if?
Show answer
It prints “You need a library card.” and then “Check finished.” Java skips the whole cardholder block, so it does not test bookAvailable in the inner if.
Exercise
In the example without braces, a cardholder with an unavailable book gets the card reminder. Why does shifting the else to the left not fix it, and where should the outer if block close?
Show answer
Indentation does not change which if owns the else. Close the outer if block after the entire inner book check and before the else that prints the card reminder.
Exercise
In the hold example, where should you add “Thanks for checking.” so it prints for an available book, an unavailable book that allows holds, and an unavailable book that does not allow holds?
Show answer
Put it after the closing brace of the outer else block, but still inside main. All three paths reach that spot.