The switch
statement in Java is a control flow statement that allows you to execute one out of multiple code blocks based on the value of an expression. It is often used as an alternative to multiple if-else
statements when you have a single variable to compare against multiple possible values.
The switch
statement improves the readability and efficiency of your code when you need to compare a variable to several potential values.
In this guide, we'll explore the switch
statement in detail, including its syntax, how it works, and provide examples of its usage.
The switch
statement is used to evaluate an expression and match its value against one or more predefined cases. The matching case executes the corresponding block of code. If no case matches the value, an optional default
case can be executed.
The switch
statement provides a cleaner and more efficient way of handling multiple conditions compared to using a series of if-else
statements. It is typically used when a variable can take one of several discrete values, such as an integer, character, or string.
The syntax for the switch
statement is straightforward:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
case value3:
// Code to execute if expression equals value3
break;
// More cases as needed
default:
// Code to execute if no case matches
}
case
has an associated block of code that gets executed if the case value matches the expression.break
is used to terminate the switch
statement and prevent it from falling through to the next case.default
case is optional. It’s executed when none of the case
values match the expression.When a switch
statement is executed, the following steps occur:
case
value in the switch
statement.case
, the break
statement is executed to exit the switch
statement. If no break
is used, execution will "fall through" to the next case.default
block is provided, the code inside the default
block will be executed.Let’s explore some examples of how to use the switch
statement in Java.
Here’s a simple example using a switch
statement with an integer value:
public class SwitchExample {
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;
default:
System.out.println("Weekend");
}
}
}
Explanation:
switch
statement checks the value of the day
variable.day
is 3, the program prints "Wednesday".break
statement ensures that the program exits the switch
after executing the matching case.
Wednesday
Java allows you to use a switch
statement with strings as well. Here’s an example:
public class SwitchWithString {
public static void main(String[] args) {
String day = "Sunday";
switch (day) {
case "Monday":
System.out.println("Start of the work week");
break;
case "Friday":
System.out.println("Almost weekend!");
break;
case "Sunday":
System.out.println("Weekend!");
break;
default:
System.out.println("Middle of the week");
}
}
}
Explanation:
switch
statement compares the string day
with the case
values.day
is "Sunday", the program prints "Weekend!".
Weekend!
You can group multiple cases in a switch
statement. This allows you to run the same code block for several cases:
public class SwitchMultipleCases {
public static void main(String[] args) {
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
System.out.println("Excellent");
break;
case 'C':
System.out.println("Good");
break;
case 'D':
System.out.println("Fair");
break;
default:
System.out.println("Invalid grade");
}
}
}
Explanation:
case 'A'
and case 'B'
are grouped together, meaning that both will result in the message "Excellent" being printed.grade
is 'B'
, the output is "Excellent".
Excellent
The break
statement in the switch
statement is essential. It ensures that once a case is executed, the program control exits the switch
. Without the break
, the program will continue executing the next case (this behavior is known as fall-through).
Here’s an example to demonstrate fall-through:
public class SwitchWithoutBreak {
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("Invalid number");
}
}
}
Explanation:
break
statements, once case 2
is matched, the program will execute all subsequent cases until the switch
block ends.
Two
Three
Invalid number
The default
case is optional but highly recommended as a fallback option. It is executed if none of the specified cases match the value of the expression.
Here’s an example:
public class SwitchWithDefault {
public static void main(String[] args) {
int number = 6;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Invalid number");
}
}
}
Explanation:
default
case is executed.
Invalid number
From Java 12, the switch
statement introduced a new switch expression. This allows you to return a value from the switch
statement, making it more versatile.
Here’s an example:
public class SwitchExpression {
public static void main(String[] args) {
int day = 3;
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
System.out.println(result);
}
}
Explanation:
->
for specifying the case blocks.switch
expression and can be assigned to a variable.
Wednesday
switch
statement is most useful when comparing a variable against discrete values, such as integers, characters, or strings.switch
is not suitable for conditions that involve ranges or complex logic (for that, use if-else
).default
case to handle unexpected values, especially when dealing with user input or unknown values.