Thursday, September 28, 2023

Java 14: Enhanced Switch Expressions

3 min read
(Updated: Thursday, September 28, 2023)

1. Introduction

Remember the days when working with Java's switch statements felt like navigating through a maze of break statements and verbose case labels? How often did you wish for a more elegant, less error-prone way to handle multiple conditions? In Java 12 or later, we all should leverage the "Enhanced Switch Statements," a feature that simplifies the traditional switch syntax, allowing developers to write more concise, readable, and maintainable code.

Let's also look into some illustrative examples to help better understand and utilize this powerful new feature.

2. What is it?

The enhanced switch expression introduced in Java 12 as a preview feature, and finalized in Java 14 allows for more concise and readable code.

Before talking about its benefits, let's first take a look at the traditional switch statement, and compare it with the new enhanced switch expression.

3. Put it in action

In this case, we'll convert the numeric representation of a month (1-12) to its corresponding number of days, taking into account that February can have 28 or 29 days depending on whether it's a leap year.

Traditional Switch Statement:

Java
int month = 2;
int year = 2020;
int days;

switch (month) {
    case 4: case 6: case 9: case 11:
        days = 30;
        break;
    case 2:
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            days = 29;
        } else {
            days = 28;
        }
        break;
    default:
        days = 31;
        break;
}

System.out.println("Days: " + days); // Output: Days: 29

As comparison, now let's look at the Enhanced Switch Statement:

Java
int month = 2;
int year = 2020;
int days = switch (month) {
    case 4, 6, 9, 11 -> 30;
    case 2 -> ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;
    default -> 31;
};

System.out.println("Days: " + days); // Output: Days: 29

As you can see, in this example, the enhanced switch statement simplifies the syntax by using the new "->" operator and combining multiple case labels with a comma. It also incorporates a ternary conditional expression to determine the number of days in February, making the code more concise and readable.

4. Why Enhanced Switch Expressions

  1. Conciseness: The new switch expression is more compact, as it eliminates the need for 'break' statements and reduces boilerplate code.
  2. Improved Readability: By using the "->" syntax, the enhanced switch expression is easier to read and understand, making it simpler to identify the relationship between a case and its corresponding result.
  3. Safer Code: The enhanced switch expression reduces the risk of fall-through cases, which occur when the 'break' statement is accidentally omitted. This helps prevent unintended behavior and potential bugs in your code.
  4. Expression-Oriented: The new switch syntax returns a value, allowing for more functional-style programming and seamless integration with other expressions.

5. One more thing

Pattern Matching: The switch expression enhancement also introduces pattern matching, which is a preview feature in Java 17, to simplify type-testing and type-casting:

Java
Object obj = "Hello, Java 17!";
String result = switch (obj) {
    case Integer i -> String.format("Integer: %d", i);
    case String s -> String.format("String: %s", s);
    default -> "Unknown";
};

In the example above, the switch statement automatically performs type-testing and type-casting, allowing for cleaner and more efficient code.

6. Conclusion

The enhanced switch expression is a powerful feature that improves upon the traditional switch syntax by providing a more concise, readable, and safe way to handle multiple cases.

With the addition of yielding values and pattern matching, this feature is a valuable tool for any Java developer looking to write more efficient and maintainable.

You might want to check these out ↘

How Your Database Stands Up to the Ultimate Reliability Check: ACID rules

How Your Database Stands Up to the Ultimate Reliability Check: ACID rules

For IT professionals in database management, grasping the core principles that protect our digital transactions is essential. Today, we're exploring the ACID model, a pivotal framework for ensuring transaction reliability and security. This goes beyond mere theoretical knowledge; it's vital for the smooth operation of diverse systems, from financial processes to social media platforms. We'll delve into the ACID principles and their critical role in real-world applications.
Convert String to Date: The Java Ways

Convert String to Date: The Java Ways

Converting strings to dates in programming is a common task that's more complex than it seems. This challenge is rooted in the wide range of date formats and the specifics of time zones. Converting a String to a Date in Java can be done in several ways, depending on the Java version you're using and whether you are incorporating external libraries. Below are the primary methods used in different versions of Java and through some commonly used external libraries.
Cookbook: How to Effectively Revert a Git Commit

Cookbook: How to Effectively Revert a Git Commit

As a software engineer, encountering situations where recent changes need to be undone is not uncommon. It may be due to errors, or in some cases just need a significant rework. When such scenarios arise while using Git as your version control system, there’s a few approaches that can help revert those changes effectively. Let’s take a closer look.
Technology
Trending
Contact Us

Stay ahead of the curve
on software insights and technology trends.