Switch-Case

Switch-Case

There is nothing that helps a developer like a switch case statement. With multiple conditions and business logic to check, switch case is a boon.

With the advent of Java 21 and the usage of yield statement, switch-case statements help greatly in reducing the cyclometric complexity of the functions and improving the readability of the code. In addition to maintenance, it enhances the performance internally too.

There are some complex ways in which JVM stores these structures - tableswitch (where everything is stored as an array-like structure where the index corresponds to the case value) or a lookupswitch (where JVM creates a table of case values and their corresponding jump targets in the bytecode) or a hash-based approach for strings. Nevertheless, one can confidently say switch-case statements are better than normal conditionals for many reasons.

Let's look at some ways with which we can use switch-case statements in your Java code the next time.

  1. The traditional way

public String getDayTraditional(int day) {
        String dayName;
        switch (day) {
            case 1: dayName = "Monday"; break;
            case 2: dayName = "Tuesday"; break;
            case 3: dayName = "Wednesday"; break;
            case 4: dayName = "Thursday"; break;
            case 5: dayName = "Friday"; break;
            case 6: dayName = "Saturday"; break;
            case 7: dayName = "Sunday"; break;
            default: dayName = "Invalid day"; break;
        }
        return dayName;
    }        

2. The modern switch expression - one of my favourites

public String getDayExpression(int day) {
        return switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Invalid day";
        };
    }        

3. Using yield. Very good when you need to combine multiple actions before returning a value.

public String getDayWithYield(int day) {
        return switch (day) {
            case 1: yield "Monday";
            case 2: yield "Tuesday";
            case 3: yield "Wednesday";
            case 4: yield "Thursday";
            case 5: yield "Friday";
            case 6: yield "Saturday";
            case 7: yield "Sunday";
            default: yield "Invalid day";
        };
    }        

4. Combine with multiple case labels. Very handy when we need to perform the same actions for multiple values.

public String getDayCategory(int day) {
        return switch (day) {
            case 1, 2, 3, 4, 5: yield "Weekday";
            case 6, 7: yield "Weekend";
            default: yield "Invalid day";
        };
    }        

5. Guarded patterns. Helps to combine multiple conditions before executing for a given matching value.

return switch (obj) {
    case Integer i -> "Integer";
    case String s -> "String";
    case Employee employee && employee.getDepartment().equals("IT") -> "IT Employee";
    default -> "Some other type";
};        

With multiple options, come multiple choices. How to write your switch-case?

  • Start with the arrow syntax (->) as your default choice
  • Move to pattern matching if you need more complex conditions
  • Use yield if you need multiple statements in your cases

Happy coding!

Vivek V

Tech Enthusiast | Software Engineer | LinkedIn Top Voice | Blogger | Podcaster | Newsletter Author

2 个月

Very helpful

VADIVEL PM

Spring-Boot|Micro-Services|Docker|Kubernetes

2 个月

Excellent example

要查看或添加评论,请登录

Preethi Pattabiraman的更多文章

  • MongoDB Operators

    MongoDB Operators

    MongoDB provides a wide range of intuitive operators that help us to query the collections for the relevant documents…

    1 条评论
  • Java Integer Cache

    Java Integer Cache

    I was astounded to learn about this feature in Java called the IntegerCache. A new functionality was added to reduce…

  • Circuit Breaker

    Circuit Breaker

    A microservice always needs its friends, the supporting microservices. They all collaborate to make an application…

    1 条评论
  • REST API - Content Negotiation

    REST API - Content Negotiation

    Please find part 1 of this series in the above link. Generally, REST resources can have multiple representations of the…

    1 条评论
  • REST API - Documentation

    REST API - Documentation

    There are some basic REST API features that are expected from any API, such as Documentation Content Negotiation I18N…

    9 条评论
  • Finally

    Finally

    Many of the interview questions are aimed to make us pause. But, if you note those little pointers, it will be a…

社区洞察

其他会员也浏览了