Java 12 Switch Expressions

java 12 switch expressions

Oracle will release Java 12 in March and it comes with a handful of new features. I’m going to cover them in the next few posts. We’ll start this week with switch expressions. I’ll take a look at how they change how you’ll use the language.

A Basic Class

Let’s start with a simple car class.

Car has an enum that indicates whether it’s a standard, deluxe, or limited model. We’ll going to use this flag to manage the car’s different features.

Standard Switch Statement

So, it makes sense that we’d use a switch statement to manage features.

Let’s set up a method to set the number of cylinders based on the model:

We could write this without the local cylinders variable, of course. I started with an example that uses break statements to demonstrate a typical switch.

Here’s a simplified version:

Without the local variable, we need a default case to be sure a value is returned from the method.

Either way, switch statements are a little noisy.

Java 12 Switch Expressions

Java 12 makes this easier to write. You can use a switch expression:

As the name implies, this new switch is an expression, not just a statement. It returns a value. So, the question of whether to use a local variable when selecting a case goes away.

It’s also much easier to read since we don’t need breaks, and each case fits on a single line.

But, you can still use multiple lines in a case if you need to. Let’s say you want to add another field to Car and use it to change the result of getCylinders(). You can add a code block inside the case, and use a break to return a value.

Even though this adds a couple of break statements, it’s still cleaner and easier to follow than a switch statement.

I’m looking forward to moving to Java 12. Stay tuned for more!

Photo by Karim MANJRA on Unsplash

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

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