Java 14 Tutorial
Selected Reading
- Java 14 - Discussion
- Java 14 - Useful Resources
- Java 14 - Quick Guide
- Java 14 - Deprecation & Removals
- Java 14 - Others
- Java 14 - NUMA Aware G1
- Java 14 - Packaging Tools
- Java 14 - NullPointerException
- Java 14 - pattern for instanceOf
- Java 14 - Text Blocks
- Java 14 - Switch Expressions
- Java 14 - Environment Setup
- Java 14 - Overview
- Java 14 - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 14 - Switch Expressions
Java 14 - Switch Expressions
Java 12 introduces expressions to Switch statement and released it as a preview feature. Java 13 added a new yield construct to return a value from switch statement. With Java 14, switch expression now is a standard feature.
Each case block can return a value using yield statement.
In case of enum, default case can be skipped. In other cases, default case is required.
Example
Consider the following example −
ApiTester.java
pubpc class APITester { pubpc static void main(String[] args) { System.out.println("Old Switch"); System.out.println(getDayTypeOldStyle("Monday")); System.out.println(getDayTypeOldStyle("Saturday")); System.out.println(getDayTypeOldStyle("")); System.out.println("New Switch"); System.out.println(getDayType("Monday")); System.out.println(getDayType("Saturday")); System.out.println(getDayType("")); } pubpc static String getDayType(String day) { var result = switch (day) { case "Monday", "Tuesday", "Wednesday","Thursday", "Friday": yield "Weekday"; case "Saturday", "Sunday": yield "Weekend"; default: yield "Invapd day."; }; return result; } pubpc static String getDayTypeOldStyle(String day) { String result = null; switch (day) { case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": result = "Weekday"; break; case "Saturday": case "Sunday": result = "Weekend"; break; default: result = "Invapd day."; } return result; } }
Compile and Run the program
$javac APITester.java $java APITester
Output
Old Switch Weekday Weekend Invapd day. New Switch Weekday Weekend Invapd day.Advertisements