Java 12 Tutorial
Selected Reading
- Java 12 - Discussion
- Java 12 - Useful Resources
- Java 12 - Quick Guide
- Java 11 Tutorial
- Java 10 Tutorial
- Java 9 Tutorial
- Java 8 Tutorial
- Java Tutorial
- Java 12 - Microbenchmark
- Garbage Collection Enhancements
- Java 12 - String methods
- Java 12 - Teeing Collectors
- Java 12 - Compact Number Formatting
- Java 12 - File mismatch method
- Java 12 - Switch Expressions
- Java 12 - Environment Setup
- Java 12 - Overview
- Java 12 - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 12 - Switch Expressions
Java 12 - Switch Expressions
Java 12 introduces expressions to Switch statement and released it as a preview feature. Following are the changes introduced in case of new switch with expressions −
No fallthrough.
No break statment required to prevent fallthrough.
A single case can have multiple constant labels.
Default case is compulsary now.
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) { String result = switch (day) { case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> "Weekday"; case "Saturday", "Sunday" -> "Weekend"; default -> { break "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 -Xpnt:preview --enable-preview -source 12 APITester.java $java --enable-preview APITester
Output
Old Switch Weekday Weekend Invapd day. New Switch Weekday Weekend Invapd day.Advertisements