Saturday 22 May 2021

Java13: Switch expression

From Java 13 onward, you can use switch statement either as a statement or an expression (This feature is already available in Java12 preview mode).

 

Switch expressions bring clear and safe code. Let us see it with an example.

 

SwitchExpressionDemo1.java

package com.sample.app.switchexp;

public class SwitchExpressionDemo1 {
	public static void main(String args[]) {
		int number = 2;

		String result = switch (number) {
		case 2:
			yield "Number is even and prime";
		case 3, 5:
			yield "You choose a prime number and it is < 7";
		case 4, 6:
			yield "You entered even number and it is < 8.";
		default:
			yield "You entered a number";
		};

		System.out.println(result);
	}

}

 

Output

Number is even and prime

 

1. As you see above snippet, value returned from switch expression is assigned to the variable ‘result’.

2. If you have multiple case statements that matches to same business logic, you can separate case conditions by comma operator.

 

Example

case 3, 5: yield "You choose a prime number and it is < 7";

 

 

Reference

https://openjdk.java.net/jeps/354


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment