Switch Expressions And The Right Way To Use Them

July 16, 2020
Switch Expressions



Every Java developer knows about switch statements. There is no question about that. We’ve all used it. And we are used to it. Recently, Java 12 introduced switch expressions. These were further refined in Java 13.

With switch expressions, the entire switch block returns a value that can then be assigned. You can use a lambda-style syntax. And have a straightforward control flow that is also free of fall-through.

Below is a very basic code using switch expressions in Java 13:

package com.mycode.java13;

public class ABC {

public static void main(String[] args) {

System.out.println(returnValue("one"));
System.out.println(returnValue ("two"));
System.out.println(returnValue ("three"));
}

private static int returnValue (String mode) {
int value = switch (mode) {
case "one" -> 1;
case "two" -> 2;
default -> -1;
};
return value;
}

}

Output:
1
2
-1

Expression vs Statement

Now, if you’re top tech talent, you’re asking what all the other Java developers are asking too. We’ve been using switch from the start. What’s new about switch expressions?

Well, switch used to be a statement in Java. It used to direct control flow and control the branching. It showed the way. Switch expressions not only provide guidance but also get results in the form of a value.

If you want to calculate a value, you can assign the result to a variable. Then use break in switch statement to get out. Now, the complete switch expression is checked by picking the respective switch branch and executing it. The result can be assigned to a variable.

One noticeable change is that a switch expression needs to end with a semicolon. The old switch statement did not need this. It will take some time. But you’ll get used to it.

This does not mean you cannot use switch statements at all now. The JDK Enhancement Proposal mentions that switch expression extends switch. So it can be either be used as a statement. Or as an expression. This change will simplify things for Java coders. It also presents a way to use pattern matching (JEP 305) in switch.

How To Use Labels: Arrow (->) And Yield

In the first example, you must’ve observed the new ‘lambda-style’ syntax with the arrow between label and execution. You are not required to use switch as an expression. In switch, we all are familiar with fall-through. A case label determines where the control flow jumps. But it needs a break or return to stop flowing through the switch.

The arrow-form prevents fall-through. It signifies that only the block on its right will be executed. The only difference is that by using the arrow label, there is no fall-through. If you still want to have the fall-through option, use the “yield” keyword.

Below is the same code used in the first example, with yield instead of arrow label:

private static int usingYield(String mode) {
int value = switch (mode) {
case "one":
yield 1;
case "two":
yield 2;
default:
yield -1;
};
return value;

Note that you need to use the new keyword “yield” to express which value each branch results in. This has been implemented in Java 13. In Java 12, break was used in a way similar to its use in Java statements, i.e. break 2; instead of yield 2; .

Another feature that comes with label’s arrow is that it can point to a single statement (like above). But it can also point to a curly-braced block to execute the whole block if the condition is met.

Characteristics Of Using Switch Expression

Here are some characteristics of using switch as an expression instead of as a statement:

Poly Expressions

Switch expressions are poly expressions. This means they do not have a specific defined type. There can be several types. Poly expressions can be lambdas, function or unary operators.

Returning Early

One effect of using a switch expression is that you can return from inside a switch statement. But you cannot return from within an expression.

Statement

private static int usingStatement(String mode) {
    switch (mode)
        case “one” -> { return 1; }
        default -> { return -1; }
    };
}
// `return` is only possible from inside block

Expression

private static int usingStatement(String mode) {
    String result = switch (mode) {
case “one” -> { return 1; }
        default -> { return -1; }
    };
}
//This will not compile and will prompt an error.

Missing a Case

In your career as a software developer, you must have missed a case many times! And of course the code starts behaving in ways it’s not supposed to! But the compiler cannot help you here – It’s up to you to find and correct it. Even the best talent in technology will take time. Especially if it’s a long thread of code, and the mistake is buried deep inside.

Switch expressions offer a way out. What should switch check to prompt an error if a case is missed? The only solution in Java is ‘null’ for reference types and the ‘default value’ for primitives. This would be a very error-prone approach. It will probably cause search for error through the codebase.

Switch expressions insist that all possible cases are covered. Otherwise, there will be a compile error.

Conclusion

Many elite software engineers have developed the ideas in JDK Enhancement Proposal. Every Java developer should explore such new features to make coding easier. This practice expands one’s knowledge. It also sets you on the right path to become a top software developer.



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US