Java Switch Statement
Introduction to Switch
The switch statement in Java allows selecting one block of code to execute out of multiple possible branches, based on the value of a single variable or expression.
It is often used as a more readable and efficient alternative to long chains of if-else statements when checking the same variable against different constant values.
public class SwitchIntro {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Wednesday
How It Works
The expression inside the switch is evaluated once, and its result is compared with the values of each case label.
When a match is found, the code for that case runs until a break statement is reached or the switch block ends.
If no case matches, the default block executes (if provided).
Switch with Strings
Since Java 7, switch statements can also operate on String values.
This is useful for handling multiple constant string comparisons, such as user input or command keywords.
public class SwitchWithStrings {
public static void main(String[] args) {
String fruit = "Apple";
switch (fruit) {
case "Apple":
System.out.println("It's an apple.");
break;
case "Banana":
System.out.println("It's a banana.");
break;
default:
System.out.println("Unknown fruit.");
}
}
}
It's an apple.
Switch Without Break
If a break statement is missing, execution continues into the next case (a behavior called fall-through).
This can be intentional when multiple cases should share logic, but can cause errors if done accidentally.
public class SwitchFallThrough {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
default:
System.out.println("Default case");
}
}
}
Two Three Default case
Enhanced Switch (Java 14+)
Java 14 introduced the enhanced switch expression, which allows using switch as an expression that returns a value.
It uses the arrow (->) syntax to eliminate fall-through and can directly assign results to variables.
public class EnhancedSwitch {
public static void main(String[] args) {
int day = 5;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
System.out.println(dayName);
}
}
Friday