Core Java Tutorial

Core Java Tutorial

Java 12, 13, 14 Switch expressions Updates

Java 12 – Switch expressions

Java 12 JEP 325 Extend switch so it can be used as either a statement or an expression, and so that both forms can use either traditional case … : labels (with fall through) or new case … -> labels

Example (traditional approach using : operator)

public class SwitchTest {
	
	public static void main(String[] args) {
		
		String day="SUN";
			
		switch(day)
		{
		case "MON": 
			System.out.println("Working day");
			break;
			
		case "TUE":
			System.out.println("Working day");
			break;
			
		case "WED":
			System.out.println("Working day");
			break;
			
		case "THU":
			System.out.println("Working day");
			break;
			
		case "FRI":
			System.out.println("Working day");
			break;
			
		case "SAT": 
			System.out.println("Half Working day");
			break;
		
		case "SUN": 
			System.out.println("Holiday day");
			break;
			
		default:
			System.out.println("Invalid day");
		}
		
	}

}

Example using Java 12 expression (->)

public class SwitchTest {
	
	public static void main(String[] args) {
		
		String day="SUN";
			
		switch(day)
		{
		case "MON","TUE","WED","THU", "FRI" -> 	 System.out.println("Working day");

		case "SAT"->   System.out.println("Half Working day");
		
		case "SUN"->   System.out.println("Holiday day");
		
		default-> 	 System.out.println("Invalid day");
		};	
	}
}