The switch
statement is a control structure used to perform multi-way branching based on the value of a specific variable or expression. Unlike if
statements, which can handle complex conditions, a switch
statement is ideal for scenarios where you need to compare a variable against multiple specific values, allowing for a cleaner, more readable structure for certain types of code.
switch
StatementThe basic syntax of a switch
statement is as follows:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// More cases as needed
default:
// Code to execute if no case matches
break;
}
expression
is evaluated once and compared to each case
value.case
represents a specific value to compare against.break
is used to exit the switch
block after a matching case executes, preventing “fall-through” (where code continues executing subsequent cases).default
is optional and runs if no other case matches. It acts as a catch-all similar to an else
in an if-else
structure.switch
Statementint day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("The day is: " + dayName);
In this example, dayName
will be set to "Wednesday"
because day
has a value of 3
.
switch
Statementswitch
statement in Java can handle int
, char
, String
, enum
, and short
.case
does not end with break
, control “falls through” to the next case, which may lead to unintended results.default
Case: Including the default
case is generally recommended, even if you think all possible cases are covered, to handle unexpected values.switch
In this example, a switch
statement processes different commands.
String command = "start";
switch (command) {
case "start":
System.out.println("System is starting...");
break;
case "stop":
System.out.println("System is stopping...");
break;
case "restart":
System.out.println("System is restarting...");
break;
default:
System.out.println("Unknown command");
break;
}
switch
Expressions (Java 12+)Starting from Java 12, switch
can be used as an expression, which allows for more concise code:
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("The day is: " + dayName);
In this example, the switch
expression directly returns a value, making the code cleaner and removing the need for break
statements.
switch
vs if-else
switch
when you have multiple specific values to check, especially with int
, char
, String
, or enum
.if-else
for complex conditions or ranges (e.g., if (x > 10 && y < 20)
).