The default Case and Exhaustiveness
What You'll Learn
You'll learn how the default case in a traditional switch statement acts as a safety net, catching any values that don't match your explicit case labels.
The Catch-All Case
Think of a switch statement like a mail sorting center. Each case label is like a specific mailbox for certain addresses. But what happens when a letter arrives that doesn't match any mailbox? Without a plan, it just falls through the cracks. That's where default comes in—it's the "everything else" bin.
The default case handles any value that doesn't match any of your specified cases:
int dayOfWeek = 9; // Invalid day number
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
In this example, since 9 doesn't match cases 1, 2, or 3, the default case executes, printing "Invalid day".
Exhaustiveness: Covering All Bases
Exhaustiveness means accounting for every possible value your variable might have. The default case is your tool for achieving this. Even if you think you've covered all realistic scenarios, unexpected values can appear (user input errors, bugs, future code changes).
You can place default anywhere among your cases—it doesn't have to be last, though that's conventional for readability. It executes whenever no other case matches, regardless of position.
switch (choice) {
default:
System.out.println("Unknown choice");
break;
case 1:
System.out.println("Option one");
break;
}
Key Takeaway: The default case ensures your switch statement handles unexpected values gracefully, preventing silent failures and making your code more robust and maintainable.