An insight into the Switch Expression in Java

Pradeesh Kumar
4 min readNov 22, 2022

--

Photo by Clever Sparkle on Unsplash

The switch statement has been there in Java since its beginning. It eliminates the need of writing an if-else-if ladder to evaluate an expression against a set of values. However, there are some downsides to the switch statement, a few of them are the fall-through, too many break statements, inability to obtain the results, local variable scope etc.

What is the Switch Expression?

Switch expression was introduced in Java 12. It introduced “arrow case" labels that eliminate the need for break statements to prevent fallthrough. Also, we will be able to get the result from the Switch expression using theyeild keyword.

An example, written in the Switch statement.

public enum Day { 
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}


Day day = Day.WEDNESDAY;
int sales = 0;

switch (day) {
case SUNDAY:
case MONDAY:
case FRIDAY:
sales = 12;
break;
case WEDNESDAY:
sales = 18;
break;
case TUESDAY:
case SATURDAY:
sales = 2;
break;
case THURSDAY:
sales = 29;
break;
}
System.out.println(sales);

We can write the same above logic using the Switch Expression as follows.

Day day = Day.WEDNESDAY;
int sales = switch (day) {
case SUNDAY, MONDAY, FRIDAY -> 12;
case WEDNESDAY -> 18;
case TUESDAY, SATURDAY -> 2
case THURSDAY -> 29
}

The ‘yield’ keyword

Each case in the switch statement can have a body that executes a number of statements. Theyield keyword has been introduced to return a value from the switch expression.

int sales = switch (day) {
case SUNDAY, MONDAY, FRIDAY -> {
System.out.println("Not bad");
yield 12;
};
case WEDNESDAY -> {
System.out.println("Average");
yield 18;
};
case TUESDAY, SATURDAY -> 2 // The yield is not necessary if the case evaluates a single expression
case THURSDAY -> 29
}

It’s not always mandatory to return a value from the switch expression. We can also have some statements in each case. However, we cannot mix the cases which return a value and some that don’t.

// COMPILATION ERROR
int sales = switch (day) {
case SUNDAY, MONDAY, FRIDAY -> {
System.out.println("Not bad"); // The case must return a value
};
case WEDNESDAY -> {
System.out.println("Average");
yield 18;
};
case TUESDAY, SATURDAY -> 2
case THURSDAY -> 29
}
// Switch expression with only statements. This doesn't return any value.
switch (day) {
case SUNDAY, MONDAY, FRIDAY -> System.out.println("Good");
case WEDNESDAY -> System.out.println("Average");
case TUESDAY, SATURDAY -> System.out.println("Bad");
case THURSDAY -> System.out.println("Great!");
}

Default Case

In the above examples, the default case is not used since all the enum values are covered in cases. What if we didn’t include SUNDAY in the above example? What would the switch expression return if the specified day is SUNDAY? Hence, when a switch expression returns a value, a default case is always required.

As shown in the below example, the case doesn’t cover SUNDAY and MONDAY. Hence, a default case is required since it returns a value.

Day day = Day.WEDNESDAY;
int sales = switch (day) {
case FRIDAY -> 12;
case WEDNESDAY -> 18;
case TUESDAY, SATURDAY -> 2
case THURSDAY -> 29
default -> 0
}

The null Case

The Switch statement doesn't support null values, passing a null value throws a NullPointerException.

Java 17 has added the ability to a null case in the switch expression.

String weather = null;
switch (weather) {
case null -> System.out.println("Not mentioned");
case "rainy" -> System.out.println("Carry an umbrella");
case "cold" -> System.out.println("Carry a Jacket");
case "hot" -> System.out.println("Carry a Hat");
}

Scope of Local variable inside Case

In Switch statement, the scope of a variable declared in a case is the entire statement. A variable declared in one case exists in all the cases.

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
String message = "31 Days";
System.out.println(message);
break;
case 4:
case 6:
case 9:
case 11:
String message = "30 Days"; // ERROR
System.out.println(message);
break;
}

In switch expression, the variable scope is only in the case where it’s declared. Variable with the same name can be declared in other cases.

switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> {
String message = "31 Days";
System.out.println(message);
}
case 4, 6, 9, 11 -> {
String message = "30 Days"; // VALID
System.out.println(message);
}
}

Pattern matching in Switch Expression

Java 17 introduced Pattern matching in the switch expression. You can pass an object and check its type using the cases.

Object value = Integer.valueOf(12);
switch (value) {
case Integer i -> System.out.println("It is an integer");
case String s -> System.out.println("It is a string");
case Person s -> System.out.println("It is a Person");
default -> System.out.println("Unknown type!");
}
Shape shape = new Circle(12);
double area = switch (value) {
case Rectangle r -> r.getLength() * r.getWidth();
case Circle c -> Math.PI * c.getRadius() * c.getRadius();
default -> throw new IllegalArgumentException("Unknown Shape!");
}

Conclusion

The Switch expression eliminates the need of writing break statements and prevents fall through. The case may contain a body of statements and yield keyword to return a value. The code looks more readable and concise.

--

--

Pradeesh Kumar
Pradeesh Kumar

Written by Pradeesh Kumar

Distributed Systems | Cloud Computing | Databases | Software Engineering

No responses yet