Java Switch Statement Control Flow and Branching
The switch statement in Java evaluates an expression and executes code blocks based on matching case values. It provides an alternative to multiple if-else statements when comparing the same variable against multiple constant values.
Syntax Structure
switch(expression) {
case value1:
// statements
break;
case value2:
// statements
break;
// additional cases
default:
// statements
}
Key characteristics of switch statements:
- Supported expression types: byte, short, int, char, and (since Java SE 7) String
- Case labels must be constant expressions or literals matching the expression type
- Execution begins at the first matching case and continues until break or end
- The break statement terminates switch execution and transfers control afteer the switch
- Default case executes when no other cases match (position-independent but typically placed last)
Practical Examples
Grade Evaluation with Break Statements:
public class GradeEvaluator {
public static void main(String[] args) {
char performanceLevel = 'B';
switch(performanceLevel) {
case 'A':
System.out.println("Exceptional");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
case 'D':
System.out.println("Below Average");
break;
default:
System.out.println("Invalid Grade");
}
}
}
Output when performanceLevel is 'B':
Good
Fall-through Behavior Without Break:
public class FallthroughDemo {
public static void main(String[] args) {
int selector = 2;
switch(selector) {
case 1:
System.out.println("First option");
case 2:
System.out.println("Second option");
case 3:
System.out.println("Third option");
default:
System.out.println("Default option");
}
}
}
Output when selector is 2:
Second option
Third option
Default option
Controlled Fall-through with Intermediate Break:
public class ControlledFallthrough {
public static void main(String[] args) {
int code = 1;
switch(code) {
case 1:
System.out.println("Processing step 1");
case 2:
System.out.println("Processing step 2");
case 3:
System.out.println("Processing step 3");
break;
case 4:
System.out.println("Alternative processing");
break;
default:
System.out.println("No valid processing");
}
}
}
Output when code is 1:
Processing step 1
Processing step 2
Processing step 3