A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java14/switch-expressions/ below:

Java Enhanced Switch Expressions - HowToDoInJava

In Java, a switch statement generally allows the application to have multiple possible execution paths based on the value of a given expression in runtime. The evaluated expression is called the selector expression which must be of type char, byte, short, int, Character, Byte, Short, Integer, String, or an enum.

1. Switch Expressions

In Java 14, switch expressions are a standard feature. In Java 13 and Java 12, it was added as a preview feature.

public class SwitchExpressions
{
	public static void main(String[] argv)
	{
		System.out.println(isWeekDayV1_1(Day.MON));		//true
		System.out.println(isWeekDayV1_2(Day.MON));		//true
		System.out.println(isWeekDayV2(Day.MON));		//true
	}

	//1 - Return value directly

	enum Day {
		MON, TUE, WED, THUR, FRI, SAT, SUN
	};

	public static Boolean isWeekDayV1_1 (Day day)
	{
		Boolean result = switch(day) {
			case MON, TUE, WED, THUR, FRI -> true;
			case SAT, SUN -> false;
		};
		return result;
	}

	public static Boolean isWeekDayV1_2 (Day day)
	{
		Boolean result = switch(day) {
			case MON, TUE, WED, THUR, FRI : yield true;
			case SAT, SUN : yield false;
		};
		return result;
	}

	//2 - Multiple statements in case block

	public static Boolean isWeekDayV2 (Day day)
	{
		Boolean result = switch(day) {
			case MON, TUE, WED, THUR, FRI ->
			{
				System.out.println("It is WeekDay");
				yield true;
			}
			case SAT, SUN ->
			{
				System.out.println("It is Weekend");
				yield false;
			}
		};
		return result;
	}
}
2. Difference between yield and return
SwitchExpression:
	YieldStatement:
    	       yield Expression;

In the above pseudo-code:

Happy Learning !!

Sourcecode Download


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4