Use Java Switch-Case expressions in Java 17 or later

Alonso Del Arte
2 min readJan 4, 2024
Photo by Dean Brierley on Unsplash

Switch-Case fall-through has been annoying C++ and Java programmers for decades. But with Java 17 and later, there’s often a better way.

In the following simple toy example for a Hello World program in Java 8, the greeting() function always returns a message saying that the greeting for the given language is not on file, even if it happens to be just a few lines before the Return line.

    static String greeting(Locale locale) {
String str;
switch (locale.getISO3Language()) {
case "deu":
str = "Hallo Welt!";
case "eng":
str = "Hello, world!";
case "fra":
str = "Bonjour le monde!";
case "ita":
str = "Ciao mondo!";
case "jpn":
str = "こんにちは世界";
case "kor":
str = "안녕, 세계";
case "spa":
str = "\u00A1Hola, mundo!";
case "zho":
str = "\u4F60\u597D\u4E16\u754C\uFF01";
default:
str = "Greeting for " + locale.getDisplayLanguage()
+ " language not on file yet";
}
return str;
}

Here, the programmer forgot to put in Break statements to end each Case. So execution always falls through to the Default no matter what the locale is.

Even prior to Java 17, a case with a Return doesn’t need a Break, shouldn’t have one at all. So this is slightly better:

    static String greeting(Locale locale) {
switch (locale.getISO3Language()) {
case "deu":
return "Hallo Welt!";
case "eng":
return "Hello, world!";
case "fra":
return "Bonjour le monde!";
case "ita":
return "Ciao mondo!";
case "jpn":
return "こんにちは世界";
case "kor":
return "안녕, 세계";
case "spa":
return "\u00A1Hola, mundo!";
case "zho":
return "你好世界";
default:
return "Greeting for " + locale.getDisplayLanguage()
+ " language not on file yet";
}
}

But with Java 17 or later, we can use Switch-Case expressions instead of Switch-Case statements. This is much better:

    private static final String KOREAN_GREETING 
= "\uC548\uB155\uD558\uC138\uC694, \uC138\uACC4\uC785\uB2C8\uB2E4!";

public static String greeting(Locale locale) {
return switch (locale.getISO3Language()) {
case "deu" -> "Hallo Welt!";
case "eng" -> "Hello, world!";
case "fra" -> "Bonjour le monde!";
case "ita" -> "Ciao mondo!";
case "jpn" -> "こんにちは世界";
case "kor" -> "안녕, 세계";
case "spa" -> "\u00A1Hola, mundo!";
case "zho" -> "你好世界";
default -> "Greeting for " + locale.getDisplayLanguage()
+ " language not on file yet";
};
}

I assure you that this works as one hope it does. This example is drawn from a demo project of mine, run HelloWorldTest to check.

Don’t worry about remembering this. If you forget that you have Java 17 or later and use old style Switch-Case statements when you can use Switch expressions, your integrated development environment (IDE) will probably remind you. At least IntelliJ IDEA does.

--

--

Alonso Del Arte

is a Java and Scala developer from Detroit, Michigan. AWS Cloud Practitioner Foundational certified