Nested if Statements and Multiway Selection 🌶️🌶️
An if statement can contain another if statement inside its own body — this is called nesting. The inner if's condition is only ever checked if the outer condition was true in the first place; if the outer condition is false, the inner if is skipped entirely, never evaluated at all.
A chain of if / else if / else if ... / else is called multiway selection: Java checks each condition in order, top to bottom, and runs the body of the FIRST one that comes back true — every condition after that is skipped, even if it would also have been true. If none of the conditions are true and there is a trailing else, that runs instead.
1. What does this print, for x = 15?
int x = 15;if (x > 10) { if (x > 20) { System.out.println("very big"); } else { System.out.println("big"); }} else { System.out.println("small");}
2. Same code as the previous question, but x = 25. What does this print?
int x = 25;if (x > 10) { if (x > 20) { System.out.println("very big"); } else { System.out.println("big"); }} else { System.out.println("small");}
3. Same code again, but x = 5. What does this print?
int x = 5;if (x > 10) { if (x > 20) { System.out.println("very big"); } else { System.out.println("big"); }} else { System.out.println("small");}
4. In the code above, when x = 5 (so the outer condition x > 10 is false), is the inner condition x > 20 ever evaluated at all?
5. What does result end up being, for score = 95?
int score = 95;String result;if (score >= 60) { result = "Pass";} else if (score >= 90) { result = "Honors";} else { result = "Fail";}
Pass
6. The result above is probably surprising — 95 also satisfies "score >= 90", so why did result end up as "Pass" instead of "Honors"? What would you need to change about the order of the conditions to fix it?
An if-else-if chain stops at the FIRST condition that is true, checking them in the order they are written. score >= 60 is checked first and is already true for 95, so its branch runs and the else-if is never even reached — even though score >= 90 would also have been true. To fix it, check the MORE SPECIFIC condition first: test score >= 90 before testing score >= 60, so the more exclusive category gets a chance to match before the broader one catches everything.
Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.