Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constant expression require in java switch case (field is final and initialized)

Tags:

java

public static final Integer SAMPLE = 100;

public static void doSomething(int errorCode) {
    switch (errorCode) {
        case SAMPLE:
            // ...
           break;
    }
}

I got constant expression required. if i change SAMPLE to int it will get fix. why ?

like image 476
Hamid Avatar asked Nov 26 '25 00:11

Hamid


1 Answers

The relevant parts of the language spec are in JLS Sec 14.11:

Every case label has a case constant, which is either a constant expression or the name of an enum constant.

This explains why you can't use an Integer value: it's not a constant expression, since it is evaluated at runtime.

The fix is to change the case label to have a constant expression. To know what types are allowed, read on in the same section of the spec:

  • Every case constant associated with the switch statement must be assignment compatible with the type of the switch statement's Expression (§5.2).

and

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

Since you can't have a constant wrapped primitive type (Character, Byte, Short or Integer: they're all evaluated at runtime), this means that case labels can only be:

  • char
  • byte
  • short
  • int
  • String
  • An enum constant

The easiest option is to change your declaration of SAMPLE to:

public static final int SAMPLE = 100;

Note that 100 is in the guaranteed-cached range of Integer.valueOf, so there is no cost of declaring the value as a primitive: where you need a boxed value, a value is used from the cache.

like image 168
Andy Turner Avatar answered Nov 27 '25 13:11

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!