Simplify Java Conditional Logic with Switch Expressions in Java 14
This article shows how to replace verbose if‑else chains with classic switch statements and then demonstrates Java 14's enhanced switch expression using arrow syntax, eliminating the need for break statements and making the code more concise and readable.
When faced with a long series of if statements, many developers feel uncomfortable and look for a cleaner alternative.
if (flag == 1) {
log.info("didispace.com: 1");
} else if (flag == 2) {
log.info("didispace.com: 2");
} else if (flag == 3) {
log.info("didispace.com: 3");
} else if (flag == 4) {
log.info("didispace.com: 4");
} else {
log.info("didispace.com: x");
}Switch statements can simplify this pattern:
switch (flag) {
case 1:
log.info("didispace.com: 1");
break;
case 2:
log.info("didispace.com: 2");
break;
case 3:
log.info("didispace.com: 3");
break;
case 4:
log.info("didispace.com: 4");
break;
default:
log.info("didispace.com: x");
break;
}Java 14 introduces an enhanced switch expression with arrow syntax, allowing each case to be written more concisely and making the break keyword optional:
switch (flag) {
case 1 -> log.info("didispace.com: 1");
case 2 -> log.info("didispace.com: 2");
case 3 -> log.info("didispace.com: 3");
case 4 -> log.info("didispace.com: 4");
default -> log.info("didispace.com: x");
}This new syntax, part of JEP 361, was previewed in JDK 12 and JDK 13 before being finalized in JDK 14, and it streamlines conditional logic by removing the need for explicit break statements.
Tip: The JEP 361 feature was finalized in JDK 14 after two preview releases, so while some parts may appear in JDK 12/13, it is recommended to use it in JDK 14 or later.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
