‹ Back to blog

Exploring the New Switch Expressions in Java

One of the most significant changes introduced in Java 12 is the new Switch Expressions feature. Switch Expressions offer a more concise and expressive syntax for developers, making it easier to write clean and efficient code. In this article, we’ll take a closer look at Switch Expressions in Java and explore how they can help you write better code.

Traditional Switch Statements:

Consider the following switch statement that prints the number of letters of a month:

Traditional Switch Statement

New Switch Expressions:

It would be better if you could “return” the length of the month’s name instead of storing it in the variable numLetters; you can do this with a switch expression. Furthermore, it would be better if you didn’t need break statements to prevent fall through; they are laborious to write and easy to forget. You can do this with a new kind of case label 💡. The following is a switch expression that uses the new kind of case label to print the number of letters of a month:

New Switch Expression

Switch Expressions were introduced in Java 12 as a new and improved way of writing switch statements. With Switch Expressions, you no longer need break statements, and you can use any data type, including enums and Strings.

The new kind of case label has the following form:

New Case Label

Switch Expressions are a significant addition to the Java programming language, offering a more concise and expressive syntax for developers. By using Switch Expressions, you can write cleaner and more efficient code that is easier to read and maintain. While Switch Expressions do have some limitations, their benefits outweigh the drawbacks, making them a valuable tool for Java developers.