
- Java 13 Tutorial
- Java 13 - Home
- Java 13 - Overview
- Java 13 - Environment Setup
- Java 13 Language Changes
- Java 13 - Switch Expressions
- Java 13 - Text Blocks
- Java 13 - Text Block Methods
- Java 13 - Socket API Reimplementation
- Java 13 - Miscellaneous Changes
- Java 13 JVM Changes
- Java 13 - Dynamic CDS Archive
- Java 13 - ZGC Enhancements
- Java Other Versions Tutorials
- Java Tutorial
- Java 8 Tutorial
- Java 9 Tutorial
- Java 10 Tutorial
- Java 11 Tutorial
- Java 12 Tutorial
- Java 13 Useful Resources
- Java 13 - Quick Guide
- Java 13 - Useful Resources
- Java 13 - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java 13 - 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. It is still a preview feature.
Consider the following example −
ApiTester.java
Example
public class APITester { public 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("")); } public static String getDayType(String day) { var result = switch (day) { case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> yield "Weekday"; case "Saturday", "Sunday" -> yield "Weekend"; default -> "Invalid day."; }; return result; } public 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 = "Invalid day."; } return result; } }
Compile and Run the program
$javac -Xlint:preview --enable-preview -source 13 APITester.java $java --enable-preview APITester
Output
Old Switch Weekday Weekend Invalid day. New Switch Weekday Weekend Invalid day.
Advertisements