From Simple to Expressive: Java Switch Evolution: Java 13 and Beyond
Remember the days of clunky switch statements with endless break
s? Java has evolved, offering sleek switch expressions with magic like yield
and multi-case matching! This introduction will show you how to wield these new features to write cleaner, more expressive code
Here are some more Java Switch Expression examples showcasing different features:
1. Multi-case Matching(Java 14)
int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9 -> 30;
case 2 -> 28;
default -> 0;
};
In prior java versions we would do the same using this verbose code :
int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
days = 30;
break;
case 2:
days = 28;
break;
default:
throw new IllegalArgumentException("Invalid month");
}
Explanation: You can match multiple constants in a single case
clause by separating them with commas.
2. Yield (Java 13)
int value = switch (greeting) {
case "hi" -> {
System.out.println("I am not just yielding!");
yield 1;
}
case "hello" -> {
System.out.println("Me too.");
yield 2;
}
default -> {
System.out.println("OK");
yield -1;
}
};
What’s the difference to a default return?
A return
statement returns control to the invoker of a method or constructor while a yield
statement transfers control by causing an enclosing switch
expression to produce a specified value.
3. Pattern Matching for instanceOf (Java 17)
It will match the instance of the object being passed
Object obj = 42;
String message = switch (obj) {
case Integer i -> "Number: " + i;
case String s -> "String: " + s;
default -> "Unknown type";
};
System.out.println(message); // Output: "Number: 42"
Another example :
private static void printType(Object input){
switch (input) {
case Integer i && i > 10 -> System.out.println("Integer is greater than 10");
case String s && !s.isEmpty()-> System.out.println("String!");
default -> System.out.println("Invalid Input");
}
}
4. Switch expressions
A big improvement is that switch statements can be used to return a value and therefore can be used as expression. You can even return it
System.out.println(switch (x) {
case 1 -> "One";
case 2 -> "Two";
default -> "Unknown";
});