Search code examples
javaswitch-statementconstant-expressionjava-17

Benefit of using final variables in Java 17 switch-case


Can someone tell me the benefit of Java 17 accepting final expressions as a case expression in switch-case-constructs, but does not accept the final expression to be passed as a parameter?

    void test(int distinction, final int foo) {
        final var bar = 2;
        
        switch (distinction) {
        case foo -> doSomething(); // does not compile -> case expressions must be constant expressions
        case bar -> doSomething(); // does compile
        case 3 -> doOtherThings(); // does compile
        }
    }

Why doesn't the compiler accept case 1, although foo is a final variable as bar is?

In my opinion the readability of case 3 is much better than case 2. So I do not see the benefit of the new language construct.


Solution

  • Case labels must be compile time constants. A final parameter is not a compile-time constant; it may not vary across a given invocation of the method, but it can vary across invocations of the method. (Final instance fields, and static final fields without an initializer, are also not compile-time constants.)