Java Tutorial
- Java - Home
- Java - Overview
- Java - History
- Java - Features
- Java vs C++
- Java Virtual Machine(JVM)
- Java - JDK vs JRE vs JVM
- Java - Hello World Program
- Java - Environment Setup
- Java - Basic Syntax
- Java - Variable Types
- Java - Data Types
- Java - Type Casting
- Java - Unicode System
- Java - Basic Operators
- Java - Comments
- Java - User Input
Java Control Statements
- Java - Loop Control
- Java - Decision Making
- Java - If-else
- Java - Switch
- Java - For Loops
- Java - For-Each Loops
- Java - While Loops
- Java - do-while Loops
- Java - Break
- Java - Continue
Object Oriented Programming
- Java - OOPs Concepts
- Java - Object & Classes
- Java - Class Attributes
- Java - Class Methods
- Java - Methods
- Java - Variables Scope
- Java - Constructors
- Java - Access Modifiers
- Java - Inheritance
- Java - Aggregation
- Java - Polymorphism
- Java - Overriding
- Java - Method Overloading
- Java - Dynamic Binding
- Java - Static Binding
- Java - Instance Initializer Block
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java - Inner Classes
- Java - Static Class
- Java - Anonymous Class
- Java - Singleton Class
- Java - Wrapper Classes
- Java - Enums
- Java - Enum Constructor
- Java - Enum Strings
Java Built-in Classes
- Java - Number
- Java - Boolean
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Math Class
Java File Handling
- Java - Files
- Java - Create a File
- Java - Write to File
- Java - Read Files
- Java - Delete Files
- Java - Directories
- Java - I/O Streams
Java Error & Exceptions
- Java - Exceptions
- Java - try-catch Block
- Java - try-with-resources
- Java - Multi-catch Block
- Java - Nested try Block
- Java - Finally Block
- Java - throw Exception
- Java - Exception Propagation
- Java - Built-in Exceptions
- Java - Custom Exception
Java Multithreading
- Java - Multithreading
- Java - Thread Life Cycle
- Java - Creating a Thread
- Java - Starting a Thread
- Java - Joining Threads
- Java - Naming Thread
- Java - Thread Scheduler
- Java - Thread Pools
- Java - Main Thread
- Java - Thread Priority
- Java - Daemon Threads
- Java - Thread Group
- Java - Shutdown Hook
Java Synchronization
- Java - Synchronization
- Java - Block Synchronization
- Java - Static Synchronization
- Java - Inter-thread Communication
- Java - Thread Deadlock
- Java - Interrupting a Thread
- Java - Thread Control
- Java - Reentrant Monitor
Java Networking
- Java - Networking
- Java - Socket Programming
- Java - URL Processing
- Java - URL Class
- Java - URLConnection Class
- Java - HttpURLConnection Class
- Java - Socket Class
- Java - Generics
Java Collections
Java List Interface
Java Queue Interface
Java Map Interface
- Java - Map Interface
- Java - HashMap
- Java - LinkedHashMap
- Java - WeakHashMap
- Java - EnumMap
- Java - SortedMap Interface
- Java - TreeMap
- Java - The IdentityHashMap Class
Java Set Interface
- Java - Set Interface
- Java - HashSet
- Java - EnumSet
- Java - LinkedHashSet
- Java - SortedSet Interface
- Java - TreeSet
Java Data Structures
- Java - Data Structures
- Java - Enumeration
- Java - BitSet Class
- Java - Dictionary
- Java - Hashtable
- Java - Properties
Java Collections Algorithms
Advanced Java
- Java - Command-Line Arguments
- Java - Lambda Expressions
- Java - Sending Email
- Java - Applet Basics
- Java - Javadoc Comments
- Java - Autoboxing and Unboxing
- Java - File Mismatch Method
- Java - REPL (JShell)
- Java - Multi-Release Jar Files
- Java - Private Interface Methods
- Java - Inner Class Diamond Operator
- Java - Multiresolution Image API
- Java - Collection Factory Methods
- Java - Module System
- Java - Nashorn JavaScript
- Java - Optional Class
- Java - Method References
- Java - Functional Interfaces
- Java - Default Methods
- Java - Base64 Encode Decode
- Java - Switch Expressions
- Java - Teeing Collectors
- Java - Microbenchmark
- Java - Text Blocks
- Java - Null Pointer Exception
- Java - Packaging Tools
- Java - Sealed Classes
- Java - Record Classes
- Java - Hidden Classes
- Java - Compact Number Formatting
Java Miscellaneous
- Java - Recursion
- Java - Regular Expressions
- Java - Serialization
- Java - Strings
- Java - Process API Improvements
- Java - Stream API Improvements
- Java - Enhanced @Deprecated Annotation
- Java - CompletableFuture API Improvements
- Java - Array Methods
- Java - Streams
- Java - Datetime Api
- Java 8 - New Features
- Java 9 - New Features
Java APIs & Frameworks
Java Useful Resources
Java - Switch Expressions
Using switch expressions, we can return a value and we can use them within statements like other expressions. We can use case L -> label to return a value or using yield, we can return a value from a switch expression.
Java 12 introduces expressions to Switch statements and releases them as a preview feature. Java 13 added a new yield construct to return a value from a 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.
Switch Expression Using "case L ->" Labels
Java provides a new way to return a value from a switch expression using case L - > notation.
Syntax
case label1, label2, ..., labeln -> expression;|throw-statement;|block
Where label1 to labeln are representing the various values to compare and we can use expression, a statement to return a value or throw an expression.
Once Java runtime matches any label in the left block to the arrow, it moves to the right block of arrow and executes the expression(statement) and returns the result.
Switch Expression Example: Using case L -> Labels
In this example, we've compared switch expressions vs switch statement. getDayType() method takes a string input and returns the corresponding entry by evaluation switch expression and returning the value. Whereas getDayTypeOldStyle() method uses switch statement to compare each cases, uses break statement to end switch cases and to get a value, we've to set value in a variable.
package com.tutorialspoint; public class SwitchTester { 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) { // evaluate switch expression and get a value return switch (day) { case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> "Weekday"; case "Saturday", "Sunday" -> "Weekend"; default -> "Invalid day."; }; } public static String getDayTypeOldStyle(String day) { String result = null; // evaluate relevant cases and get a value into result variable 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; } }
Output
Let us compile and run the above program, this will produce the following result −
Old Switch Weekday Weekend Invalid day. New Switch Weekday Weekend Invalid day.
Switch Expression Using "case L:" Statements and the yield Statement
In java, we can get a value from switch expressio and switch statement using yield statement. yield statement returns the value and finishes the switch execution.
Syntax
case label1, label2, ..., labeln -> expression; yield value; case label1: case labeln: expression; yield value;
Switch Expression Example: Using "case L:" Statements and the yield Statement
Where label1 to labeln are representing the various values to compare and we can use expression to perform an operation and return value using yield statement.
In this example, we've compared switch expressions using yield statements. getDayType() method is using a switch expression with yield statement to get the result whereas getDayTypeStyle1() method is using switch cases with colon(:) notation with yield statement to the get the desired result.
package com.tutorialspoint; public class SwitchTester { public static void main(String[] args) { System.out.println("Old Way"); System.out.println(getDayTypeStyle2("Monday")); System.out.println(getDayTypeStyle2("Saturday")); // System.out.println(getDayTypeStyle2("")); System.out.println("New Way"); System.out.println(getDayType("Monday")); System.out.println(getDayType("Saturday")); System.out.println(getDayType("")); } public static String getDayType(String day) { return switch (day) { // we can use block statements to return a value using yield after // executing other statements case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> { System.out.println("In Weekdays"); yield "Weekday"; } case "Saturday", "Sunday" -> { System.out.println("In Weekends"); yield "Weekend"; } default -> throw new IllegalStateException("Invalid day: " + day); }; } public static String getDayTypeStyle2(String day) { return switch (day) { case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": yield "Weekday"; case "Saturday": case "Sunday": yield "Weekend"; default: throw new IllegalStateException("Invalid day: " + day); }; } }
Output
Let us compile and run the above program, this will produce the following result −
Old Way Weekday Weekend New Ways In Weekdays Weekday In Weekends Weekend Exception in thread "main" java.lang.IllegalStateException: Invalid day: at com.tutorialspoint.SwitchTester.getDayType(SwitchTester.java:26) at com.tutorialspoint.SwitchTester.main(SwitchTester.java:13)
To Continue Learning Please Login
Login with Google