Search code examples
stringeclipseswitch-statementjava-11constant-expression

Java SE 11 String Final Variable with Ternary Operator Does Not Count as a Constant Variable in Switch Case Expression


I encountered a problem that the following code doesn't work. I ran the code in Java SE 11 (11.0.8), Eclipse 2020-06, Windows 10.


Use String Final Variable with Ternary Operator: Doesn't work

public class Tester {
    public static void main(String[] args) {
        
        String switchVar = "abc";
        final String caseStr = true ? "abc" : "def";    
        switch (switchVar) {
            case caseStr: System.out.println("Doesn't work");
        }
    }
}

It has a compile time error: java.lang.Error: Unresolved compilation problem: case expressions must be constant expressions.


However, according to JLS §4.12.4 and JLS §15.28, the String type can be a final variable and ternary operator can also be counted as constant expression.

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression.

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

...

  • The ternary conditional operator ? :

  • Simple names that refer to constant variables


I did some more tests which showed either one of these points works if not combined together.

Directly use constant expression as case constant: No Problem

public class Tester {
    public static void main(String[] args) {
        
        String switchVar = "abc";
        switch (switchVar) {
            case true ? "abc" : "def": System.out.println("works");
        }
    }
}

Use String constant variable without ternary operator: No Problem

public class Tester {
    public static void main(String[] args) {
        
        String switchVar = "abc";
        
        final String VAR_A = "a";
        final String VAR_BC = "bc";
        final String CASE = VAR_A + VAR_BC;
        
        switch (switchVar) {
            case CASE : System.out.println("works");
        }
    }
}

Use int with ternary operator instead of String: No Problem

public class Tester {
    public static void main(String[] args) {
        
        int switchVar = 10;
        final int CASE = 3 > 2 ? 10 : 0;
        
        switch (switchVar) {
            case CASE : System.out.println("works");
        }
    }
}

Could anyone help me please?


Solution

  • With kindly help of others, it is sure now this is a bug of eclipse.

    I have reported the bug to eclipse. (Bugzilla – Bug 566332)