Lesson content
Read, practise, then check your understanding
An if condition must be boolean. Order an else-if chain from specific cases to general ones, use braces consistently, and prefer guard clauses to deep nesting.
Modern selection
static String result(int score) {
if (score < 0 || score > 100) return "invalid";
return switch (score / 10) {
case 10, 9, 8 -> "excellent";
case 7, 6, 5 -> "pass";
default -> "retry";
};
}
Classic colon-style switch may fall through and usually needs break. Arrow cases do not fall through and a switch expression must produce a value; a block case uses yield. Switch supports integral-compatible values, enums, strings, and increasingly expressive pattern matching in modern Java versions. Handle null deliberately where the selected language level supports it. When branching grows around types or responsibilities, polymorphism or data-driven lookup may express the model better.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.