2

I have the following:

public class Asd
{
    static final String VERSION = "version";
    static final String ECHO    = "echo".toUpperCase();
    public Asd()
    {
        String key = ECHO;
        switch (key)
        {
            case VERSION:
                break;

            case ECHO:
                break;
        }
    }
}

I get a compiler error that case ECHO: is not a constant expression. The designation final static defines a constant.

The constant ECHO will resolve from "echo" to "ECHO" when the class is instantiated. By the time the switch/case is evaluated, ECHO does equal "ECHO" and cannot be changed.

Or does a switch/case with String have some special background pointers to a String?

Because using

public class Asd
{
    static final int VERSION = 1;
    static final int ECHO    = 1 + 2;

    public Asd()
    {
        int key = ECHO;

        switch (key)
        {
            case VERSION:
                break;

            case ECHO:
                break;
        }
    }
}

Is error free even though 1 + 2 must be evaluated.

Big Guy
  • 332
  • 1
  • 13
  • 1
    That should answer your question: https://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant/3827488 – Mirek Pluta Nov 17 '21 at 19:26
  • See the Java Language Specification for _constant expressions_: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 – Louis Wasserman Nov 17 '21 at 19:27
  • @MirekPluta The referred question uses ```int```, so does not apply. – Big Guy Nov 17 '21 at 19:29
  • @LouisWasserman I have used this same method```toUpperCase()``` in static final before, but only when doing ```if/else``` constructs. Thought I'd give the new case String functionality a try – Big Guy Nov 17 '21 at 19:30
  • 2
    It must be ***compile time constants***. `1+2` and `"a"+"b"` the compiler can evaluate, but a function call (`toUpperCase()`) not. You could do `switch (key.toLowerCase())` instead. The compiler generates branches based on value comparisons. – Joop Eggen Nov 17 '21 at 19:36
  • @JoopEggen I kind of thought that is what is was. I am used to using static function calls in the static final construct, and it does work elsewhere else. Thanks – Big Guy Nov 17 '21 at 19:40
  • BTW the convention is `private static final String`; that is `final` last before (generic) type. – Joop Eggen Nov 17 '21 at 19:41
  • 1
    @JoopEggen Yeah I know actually. Typing too fast :-) – Big Guy Nov 17 '21 at 19:42
  • @MirekPluta Please remove your duplicate flag. The referred to question is about switch/case where the cases are integers, NOT Strings. My question is about String types, and therefore new – Big Guy Nov 17 '21 at 21:18

0 Answers0