Sub topic 2
Nest Decisions and Use Braces to Clarify Which else Belongs Where
Nest One Decision Inside Another
A nested decision is an if placed inside another if. Use it when the second question matters only after the first answer is yes. A block is a group of statements enclosed in braces.
Save this example as EntryCheck.java and run it.
public class EntryCheck {
public static void main(String[] args) {
boolean hasTicket = true;
boolean hasId = false;
if (hasTicket) {
if (hasId) {
System.out.println("Come in");
} else {
System.out.println("Please show ID");
}
} else {
System.out.println("Please buy a ticket");
}
}
}Java enters the outer block because hasTicket is true. The inner check is false, so its else prints “Please show ID.” If hasTicket were false, Java would skip the ID check and print “Please buy a ticket.”
Without braces, Java pairs an else with the nearest if that does not already have an else. Indenting an else to line it up with a different if does not change that rule. Use braces to show where each block ends.
Match a Selector Value to a case or default
A switch chooses where to start running code based on one value. The selector is the expression inside the switch parentheses. A case label gives a value to match against the selector. If no case matches, Java starts at default if there is one. If there is no match and no default, the switch runs nothing.
Stop Fall-Through with break
In a colon-style switch, each label ends with a colon. A break exits the switch. Without it, Java can keep running the statements under the next label, even if that label does not match. This is called fall-through.
Save this example as Menu.java and run it.
public class Menu {
public static void main(String[] args) {
int menuChoice = 2;
switch (menuChoice) {
case 1:
System.out.println("Start");
break;
case 2:
System.out.println("Settings");
break;
default:
System.out.println("Unknown choice");
}
}
}Java starts at case 2, prints “Settings,” and exits at break. The default block needs no break here because it is last.
Exercise
Remove only the break after “Settings.” What does the program print now, and why?
Show answer
It prints “Settings” and then “Unknown choice” on separate lines. Java starts at case 2 and falls through into default.