Home » Java » Core Java » Switch as an expression in Java with Lambda-like syntax

About Rafal Borowiec

Rafal Borowiec
Software developer, Team Leader, Agile practitioner, occasional blogger, lecturer. Open Source enthusiast, quality oriented and open-minded.

Switch as an expression in Java with Lambda-like syntax

As of Java 14, the switch expression has an additional Lambda-like (case ... -> labels) syntax and it can be used not only as a statement, but also as an expression that evaluates to a single value.

Lambda-like syntax (case ... -> labels)

With the new Lambda-like sytax, if a label is matched, then only the expression or statement to the right of the arrow is executed; there is no fall through:

1
2
3
4
5
6
7
var result = switch (str) {
    case "A" -> 1;
    case "B" -> 2;
    case "C" -> 3;
    case "D" -> 4;
    default -> throw new IllegalStateException("Unexpected value: " + str);
};

The above is an example of switch as an expression returning an single integer value. The same syntax can be used in switch as a statement:

01
02
03
04
05
06
07
08
09
10
11
12
13
int result;
switch (str) {
    case "A" -> result = 1;
    case "B" -> result = 2;
    case "C" -> {
        result = 3;
        System.out.println("3!");
    }
    default -> {
        System.err.println("Unexpected value: " + str);
        result = -1;
    }
}

yield

In the situation when a block is needed in a case, yield can be used to return a value from it:

1
2
3
4
5
6
7
8
9
var result = switch (str) {
    case "A" -> 1;
    case "B" -> 2;
    case "C" -> {
        System.out.println("3!");
        yield 3; // return
    }
    default -> throw new IllegalStateException("Unexpected value: " + str);
};

Mutliple constants per case

It is also possible to use mutliple constants per case, separated by comma, which futher simplifies the usage of switch:

1
2
3
4
5
6
7
var result = switch (str) {
    case "A" -> 1;
    case "B" -> 2;
    case "C" -> 3;
    case "D", "E", "F" -> 4;
    default -> 5;
};

Final example

To demonstrate new switch syntax I created this tiny calculator:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
double calculate(String operator, double x, double y) {
    return switch (operator) {
        case "+" -> x + y;
        case "-" -> x - y;
        case "*" -> x * y;
        case "/" -> {
            if (y == 0) {
                throw new IllegalArgumentException("Can't divide by 0");
            }
            yield x / y;
        }
        default -> throw new IllegalArgumentException("Unknown operator '%s'".formatted(operator));
    };
}

Source code

The source code for this article can be found on Github: https://github.com/kolorobot/java9-and-beyond

References

Published on Java Code Geeks with permission by Rafal Borowiec, partner at our JCG program. See the original article here: Switch as an expression in Java with Lambda-like syntax

Opinions expressed by Java Code Geeks contributors are their own.

0 0 vote
Article Rating
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x