Vincent Vauban’s Post

🧩☕ GUESS THE JAVA VERSION: SWITCH EXPRESSION EDITION 🔸 THE QUESTION Can you identify the first Java version that supports this code as a standard feature? 👇 class Example { public int test(String s) { return switch (s) { case "a" -> 1; case "b" -> 2; default -> 0; }; } } Which Java version is it? ▪️ Java 1.4 ▪️ Java 7 ▪️ Java 14 ▪️ Java 16 ▪️ Java 21 ▪️ Java 25 🔸 TRY BEFORE CHECKING THE ANSWER 🤔 Take a moment before reading further. This code is using a modern switch style: ▪️ the switch returns a value ▪️ the cases use -> ▪️ there is no fall-through like in the old switch form Do you have your answer? 👀 🔸 TLDR If a switch returns a value directly and uses case ->, think Java 14 ☕ 🔸 THE ANSWER ✅ The correct answer is: Java 14 This code uses a switch expression. That means the switch does not only execute code: it also produces a value that can be returned directly. The case -> syntax is part of that feature, and switch expressions became a standard Java feature in Java 14 with JEP 361. A related detail: yield is only needed when a case uses a block and must explicitly return a value from that block. In your example, each case already returns a simple value, so yield is not necessary. 🔸 WHY THIS MATTERS This is a good example of how Java became more expressive over time. With switch expressions, code is: ▪️ shorter ▪️ clearer ▪️ safer against accidental fall-through ▪️ closer to an expression-oriented style That is why this feature is easy to recognize once you know what to look for. 🔸 TAKEAWAYS ▪️ switch expressions became standard in Java 14 ▪️ case -> is a strong visual clue ▪️ yield is used only for block-style cases ▪️ This feature helps write cleaner and safer Java code #Java #OpenJDK #Java14 #Programming #SoftwareDevelopment #CleanCode #Coding #Developers #Backend #TechQuiz Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap

  • Java Switch expression

To view or add a comment, sign in

Explore content categories