When developing software, we often need to perform different actions based on specific conditions. For this, the if-else
statement is a commonly used control flow structure. However, as the number of conditions grows, especially when checking for multiple possible values of the same variable, the if-else
construct can become cluttered and harder to read. This is where the switch
statement comes to the rescue.
The switch
statement offers a more readable and structured way to make decisions based on the value of a single variable. It is especially useful when handling multiple conditions that depend on a variable's value and provides an efficient alternative to if-else
in many cases. With the introduction of the enhanced switch in Java 12 and later, the switch
statement has become even more powerful, supporting new features like expression-based switches and multiple case labels.
In this post, we'll dive into:
The basics of the
switch
statement in Java.Using nested case statements for more complex scenarios.
The new, enhanced switch introduced in Java 12+.
The Basics of the Switch Statement
The switch
statement evaluates a single expression and compares its value against multiple potential case
labels. When a match is found, the corresponding block of code is executed.
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 none of the cases match
}
expression: The variable or expression you are testing.
case value1, value2, ...: These are constant values that the expression will be compared against.
default: An optional block that runs if no
case
matches.
The break
keyword is essential to prevent "fall-through," where code execution continues through subsequent cases even after a match is found.
Example
int day = 3;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Nested Case Statements in Switch
Sometimes, the logic inside a case
statement needs to be further refined. In such scenarios, we can use a nested switch
statement to evaluate additional conditions within a case
. Although this is not common, it's useful for handling more complex logic where a hierarchy of decisions is needed.
Example
int outerSwitchVar = 1;
int innerSwitchVar = 2;
switch (outerSwitchVar) {
case 1:
switch (innerSwitchVar) {
case 1:
System.out.println("Outer: 1, Inner: 1");
break;
case 2:
System.out.println("Outer: 1, Inner: 2");
break;
}
break;
case 2:
System.out.println("Outer: 2");
break;
default:
System.out.println("No match found");
}
In this example, the outer switch controls the broader context, and the inner switch further refines it, providing a more granular control flow.
Enhanced Switch (Java 12+)
Java's enhanced switch statement, introduced in Java 12 and made a standard feature in Java 14, brings several improvements, including:
Switch expressions: A
switch
can now return values.No fall-through by default: The need for
break
statements is eliminated.Multiple case labels: You can now combine cases more elegantly.
Syntax
var result = switch (expression) {
case value1 -> "Result for value1";
case value2, value3 -> "Result for value2 or value3";
default -> "Default result";
};
Example
int day = 3;
String dayName = switch (day) {
case 1 -> "Sunday";
case 2 -> "Monday";
case 3 -> "Tuesday";
case 4 -> "Wednesday";
case 5 -> "Thursday";
case 6 -> "Friday";
case 7 -> "Saturday";
default -> "Invalid day";
};
System.out.println(dayName);
In this version of the switch
, you don’t need break
statements. The ->
symbol denotes the expression that should be executed when the corresponding case matches.
Benefits of Enhanced Switch:
Improved readability: The syntax is more concise and reduces boilerplate code.
Functional programming style: Since the
switch
can return values, it fits well into functional programming patterns.Multiple case labels: Grouping similar cases is much easier now, making code more maintainable
Now That’s it for this blog, we will meet in next blog with another topic most probably functions.
Until then Keep Learning, Keep Sharing, Keep Supporting ❤️❤️