In Java language, there are lots of improvement and new paradigm changes like lambda expression, streams, etc.
In JDK 12 you can use switch statement as an expression instead of a statement. Okay, what is the difference?
Let's write code a code to understand the difference.
In the above code, you can clearly see these switch statement with fall through structure and irritating 😠break statement. Expressing switch as a statement is error-prone, repetitive and roundabout.
In JDK 12 switch expression will come in non-fall through it means no break statement anymore.
So what does switch expression means?
Let's rewrite the above come in JDK 12 using the latest switch expression and see how many lines of code we could reduce it and how readable our code it will be.
In JDK 12 you can use switch statement as an expression instead of a statement. Okay, what is the difference?
Let's write code a code to understand the difference.
In the above code, you can clearly see these switch statement with fall through structure and irritating 😠break statement. Expressing switch as a statement is error-prone, repetitive and roundabout.
In JDK 12 switch expression will come in non-fall through it means no break statement anymore.
So what does switch expression means?
static void howMany(int k) {
System.out.println(
switch (k) {
case 1 -> "one"
case 2 -> "two"
default -> "many"
}
);
}
Let's rewrite the above come in JDK 12 using the latest switch expression and see how many lines of code we could reduce it and how readable our code it will be.
Keep it simple.
Oh ! please do remember that as this language enhancement not present in JDK 12 while compiling and running the JDK 12 code you need to add few arguments.
Please do share this with others and ask/discuss questions if you have.
Happy learning!
Oh ! please do remember that as this language enhancement not present in JDK 12 while compiling and running the JDK 12 code you need to add few arguments.
javac --enable-preview -source 12 -Xlint:preview Jdk12Switch.java
java --enable-preview -source 12 Jdk12Switch
Please do share this with others and ask/discuss questions if you have.
Happy learning!