One of the features that I am really excited about is pattern matching in Java. Pattern matching is a powerful feature in languages like Scala and Kotlin. You have an input token that’s matched against patterns.
switch-case statement comes close, yet very far, to pattern matching in Java. But starting Java 12 you’ve switch-case available as expressions and not statements, that enables us harness the power of pattern matching.
Here’s an example of using switch-case statement before Java 12.
Before
public class PatternMatching {
public static void main(String[] args) {
int number = 12;
int mod = number % 2;
String result = null;
switch(mod) {
case 1:
result = "Odd";
break;
case 0:
result = "Even";
break;
default:
result = "Huh";
};
System.out.println(result);
}
}
And an example that uses switch-case expressions in Java 12.
After
public class PatternMatching {
public static void main(String[] args) {
int number = 12;
int mod = number % 2;
String result = switch(mod) {
case 0 -> "Even";
case 1 -> "Odd";
default -> "Huh";
};
System.out.println(result);
}
}
You can compile& run PatternMatching.java by enabling preview mode like this.
javac --enable-preview --release 12 PatternMatching.java
java --enable-preview PatternMatching
You can watch the video here.