0

This is my switch statement:

    switch (aXxx.actionType()) {
        case Xxx.TYPE_A:
            break;
        case Xxx.TYPE_B:
            break;
        case Xxx.TYPE_C:
            break;
        case Xxx.TYPE_D:
            break;
    }

And this is my constant declarations (defined on another class, Xxx):

    public final static Integer TYPE_A = 610921;
    public final static Integer TYPE_B = 610922;
    public final static Integer TYPE_C = 610923;
    public final static Integer TYPE_D = 610924;

Seeing this, my compiler (I'm using IntelliJ-based Android Studio 2.1) refused to compile my code saying:

Constant expression required.

I can't understand the reason why; those are constants and I did initialize their values (unlike the case on this SO question).

I tried changing their type to primitive int, the error disappeared and my code compiled just fine.

But what's the real reason behind this?

p.s., For those who are wondering why I don't use enums for this: I work on Android and I'm intending to use those constants as @IntDef values.

Community
  • 1
  • 1
Hadi Satrio
  • 4,272
  • 2
  • 24
  • 45
  • 1
    A variable of type `Integer` is not a constant expression even if its initialization expression is. – Sotirios Delimanolis May 18 '16 at 05:26
  • I thought it's the `final static` attribute that makes an expression "constant"? – Hadi Satrio May 18 '16 at 05:27
  • Not quite. See the rules [here](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28). – Sotirios Delimanolis May 18 '16 at 05:28
  • I see. Thanks for clearing that out. You might want to post an answer instead though so I can mark it as accepted. – Hadi Satrio May 18 '16 at 05:31
  • That's not necessary. @RC found an appropriate duplicate. – Sotirios Delimanolis May 18 '16 at 05:32
  • public final static Integer TYPE_A = 610921; is object and final keyword is for object reference and not for content of object which can be changed which does not make it immutable. Check this http://stackoverflow.com/questions/4012167/java-final-modifier and http://stackoverflow.com/questions/15655012/how-final-keyword-works. – dkb May 18 '16 at 05:35

0 Answers0