0

I made a crazy discovery today in Java and I would like to know why.

The following switch statement works

public static final String OTHER_OTHER = ”.otherOther”;
…
        switch (SWITCHER) {
            case Dogs.OTHER_OTHER:
                doMyWork(intent);
                break;
            default:
                ...;
        }

Fails to compile

public static final String OTHER_OTHER = Dogs.class.getPackage().toString()+”.otherOther”;
…
        switch (SWITCHER) {
            case Dogs.OTHER_OTHER:
                doMyWork(intent);
                break;
            default:
                ...;
        }

The only difference between the two snippets is in how I constructed the constant OTHER_OTHER

The second switch statement is complaining that OTHER_OTHER is not a constant. I am creating a String of all thing, using final.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Nouvel Travay
  • 6,292
  • 13
  • 40
  • 65

1 Answers1

3

Dogs.class.getPackage().toString() is not a constant, it uses the reflection API to retrieve the package during runtime through the class-loader. So those examples are not equivalent.

Kiskae
  • 24,655
  • 2
  • 77
  • 74
  • You might add that constant values have to be resolvable at compile time, and the expression in the non-working version cannot be known until runtime. – Jim Garrison Jan 18 '16 at 23:41
  • Well, it is "constant" at run-time. but it is not a compile-time constant expression. – Thilo Jan 18 '16 at 23:42
  • @JimGarrison I believe it is correcter to say that an expression is only considered constant if it can be resolved at compile time. – Kiskae Jan 18 '16 at 23:44
  • @Thilo Which is not constant, I've seen people do some insane stuff with custom classloaders – Kiskae Jan 18 '16 at 23:45
  • My "constant" in quotes refers to "never changes after initially calculated" (which is the case here, as the field is final, and is what many people would consider a constant). But that does not matter. To be constant as per the JLS it needs to be resolved at compile-time. The switch statement makes use of that by inlining pre-calculated hashcodes into the class file. – Thilo Jan 18 '16 at 23:48
  • @Thilo Fair enough. In some cases the difference between a "constant expression" and a "constant variable" is vague. – Kiskae Jan 18 '16 at 23:50
  • Thank you so much for the discussion. Although the response itself does not answer the question and so I am not able to credit it as the answer, the discussion does indeed answer the question. The reason I cannot check it as the answer, I don't want someone else to come here, read it and don't read the discussions, and think that is the answer. – Nouvel Travay Jan 19 '16 at 21:54