Introduced as a preview in Java 12 and standardized in Java 14, switch expressions in Java extends the traditional switch statement by allowing it to be used both as a statement and as an expression. This enhancement makes code more concise, eliminates boilerplate break statements, and reduces the risk of fall‑through errors.
Java Switch expressions
A new form of switch label, written "case L ->" is one of the most notable changes that allows the code to the right of the label to execute only if the label is matched. Unlike the old switch statement, this modern approach ensures clarity and avoids accidental fall‑through.
We’ll try to understand this switch expression with an example, initially let’s use traditional switch statement to write a conditional switch-case branch and then use switch expression to see how it simplifies it.
For example if you want to determine which quarter a given month belongs to then you can group three case statements where break statement is used with only the last one in the group.
public class SwitchCaseDemo {
public static void main(String[] args) {
int month = 4;
switch(month){
case 1:
case 2:
case 3: System.out.println("Quarter 1");
break;
case 4:
case 5:
case 6: System.out.println("Quarter 2");
break;
case 7:
case 8:
case 9: System.out.println("Quarter 3");
break;
case 10:
case 11:
case 12: System.out.println("Quarter 4");
break;
default: System.out.println("Invalid month value passed");
}
}
}
Consider some of the pain areas here-
- Repetition of cases: Even if multiple cases map to the same outcome, you still need to write them on separate lines, which bloats the code.
- Verbose break usage: Every branch required an explicit break to prevent fall‑through, making the code unnecessarily verbose.
- Accidental fall‑throughs: Missing a break statement results in an accidental fall-through.
Now let’s write the same example using Java switch expressions.
public class SwitchCaseDemo {
public static void main(String[] args) {
int month = 4;
switch(month){
case 1, 2, 3 -> System.out.println("Quarter 1");
case 4, 5, 6 -> System.out.println("Quarter 2");
case 7, 8, 9 -> System.out.println("Quarter 3");
case 10, 11, 12 -> System.out.println("Quarter 4");
default -> System.out.println("Invalid month value passed");
}
}
}
Note the changes here-
- Multiple case labels can be grouped together now.
- Break statement is not required any more. If a label is matched, then only the expression or statement to the right of an arrow label is executed; there is no fall through.
- This new switch form uses the lambda-style syntax introduced in Java 8 consisting of the arrow between the label and the code that returns a value.
The new kind of case label has the following form
case label_1, label_2, ..., label_n -> expression;|throw-statement;|block
Java 12 onward you can use colon syntax (:) too with multiple case labels but in that case break statement has to be used to avoid fall-through.
public class SwitchCaseDemo {
public static void main(String[] args) {
int month = 4;
switch(month){
case 1, 2, 3: System.out.println("Quarter 1");
break;
case 4, 5, 6: System.out.println("Quarter 2");
break;
case 7, 8, 9: System.out.println("Quarter 3");
break;
case 10, 11, 12: System.out.println("Quarter 4");
break;
default : System.out.println("Invalid month value passed");
}
}
}
Why is it called Switch expression
Now the more pertinent question is why this new feature is called switch expression in Java. As you must be knowing; Statements are essentially "actions" that have to be executed. Expressions, however, are "requests" that evaluates to a value. Same difference applies to switch statement and switch expressions too.
- Traditional switch statement: Executes blocks of code based on matching cases, but does not itself yield a value.
- Switch expression: Evaluates to a value that can be directly assigned or returned, making it usable in places where a value is required.
Here is an example showing returning a value from a traditional switch statement.
public class SwitchCaseDemo {
public static void main(String[] args) {
System.out.println(getMessage("Start"));
}
private static String getMessage(String event) {
String message = "No event to log";
switch (event) {
case "Start":
message = "User started the event";
break;
case "Stop":
message = "User stopped the event";
break;
}
return message;
}
}
Output
User started the event
Same thing with Java Switch expressions. Since expression itself produces a value so it can be assigned to a variable directly.
public class SwitchCaseDemo {
public static void main(String[] args) {
System.out.println(getMessage("Start"));
}
private static String getMessage(String event) {
var msg = switch (event) {
case "Start" -> "User started the event";
case "Stop" -> "User stopped the event";
default -> "No event to log";
};
return msg;
}
}
Output
User started the event
Using yield statement with Switch expression
If you want to use colon syntax then you can assign the value directly using yield statement. The yield statement takes one argument, which is the value that the case label produces in a switch expression.
public class SwitchCaseDemo {
public static void main(String[] args) {
System.out.println(getMessage("Stop"));
}
private static String getMessage(String event) {
var msg = switch (event) {
case "Start":
yield "User started the event";
case "Stop":
yield "User stopped the event";
default:
yield "No event to log";
};
return msg;
}
}
Writing statement blocks
If you need to have multiple statements with in a case you can use a statement block enclosed in curly braces. Specify the value that the case label produces with the yield statement.
public class SwitchCaseDemo {
public static void main(String[] args) {
int month = 4;
var value = switch(month){
case 1, 2, 3 ->{
System.out.println("Quarter 1");
yield "Quarter 1";
}
case 4, 5, 6 -> {
System.out.println("Quarter 2");
yield "Quarter 2";
}
case 7, 8, 9 ->{
System.out.println("Quarter 3");
yield "Quarter 3";
}
case 10, 11, 12 -> {
System.out.println("Quarter 4");
yield "Quarter 4";
}
default -> {
System.out.println("Invalid month value passed");
yield "Invalid month value";
}
};
System.out.println("Value- " + value);
}
}
That's all for this topic Switch Expressions in Java 12. If you have any doubt or any suggestions to make please drop a comment.Thanks!
>>>Return to Java Basics Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment