Traditional switch Syntax and Case Labels
You'll learn how to use Java's switch statement to handle multiple possible values of a variable in a clean, readable way.
What is a switch Statement?
Instead of writing a long else if ladder to check if a variable equals many different values, you can use a switch statement. Think of it like a mail sorting room: packages arrive, and based on their destination code, they're sent down different chutes. Similarly, switch examines a value and directs program flow to the matching case.
Basic Syntax
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
default:
// code to execute if no cases match
}
The expression must evaluate to an int, char, byte, short, or their wrapper types (concepts you'll learn later).
How Control Flows
When the switch executes, Java compares the expression's value against each case label in order. When it finds a match, execution jumps to that case and continues downward through subsequent cases until it hits a break statement or the end of the switch block.
int day = 2;
switch (day) {
case 1:
// This won't execute
break;
case 2:
// Execution starts here!
System.out.println("Tuesday");
break;
case 3:
// This won't execute
break;
}
The break is crucial—it exits the switch. Without it, control "falls through" to the next case, which is usually unintended.
The default case is optional and acts like a final else—it runs if no other case matches.
Key Takeaway: The switch statement provides a structured way to handle multiple discrete values, using case labels to mark entry points and break statements to prevent unintended fall-through.