javaenumsswitch-statement

Enum in switch pattern causes wrong case to be used


Running in Java 21, the following code works, printing "D2" as I would expect:

public class EnumSandboxTest {

    public static void main(String[] args) {
        TestEnum test = TestEnum.D; 
        String par = "9999";
        switch (test)
        {
            case D: 
                System.out.println(par.length() < 5 ? "D2" : "D");
                break;
            case E: 
                System.out.println(par.length() < 4 ? "E2" : "E");
                break;
            default: System.out.println("EMPTY (DEFAULT)");
        };
    }   
    private enum TestEnum
    {
        D,E;
    }
}

However, if I change the switch statements to use expressions and pattern matching:

switch (test)
{
    case D -> System.out.println("D");
    case E -> System.out.println("E");
    case TestEnum p when p.equals(TestEnum.D) && par.length() < 5 -> System.out.println("D2");
    case TestEnum p when p.equals(TestEnum.E) && par.length() < 4 -> System.out.println("E2");
    default -> System.out.println("EMPTY (DEFAULT)");
};

Then the output is not "D2". Why does this occur, when par.length() is indeed less than 5 and the TestEnum "test" was set to D?


Solution

  • In your second switch statement, you are checking first for the case that test matches D, and the arrow means that case should yield/return when it matches. Since you test test to TestEnum.D, it does match, and your program is returning System.out.println("D").

    It never cycles down to the other cases. If you test for case TestEnum p when p.equals(TestEnum.D) && par.length() < 5 -> System.out.println("D2") first, above the case D, then you will get D2.