I wrote simple code in java for my Android application and got these errors.
case expressions must be constant expressionswhile private static final Integerconstant
case expressions must be constant expressions
private static final Integer
private static final Integer INVALID_USER = 901; private static final Integer SENDING_FAILED = 902; private static final Integer OK = 903; /* * * And some more project related declaration... * */ switch (responseCode){ case INVALID_USER: // logout break; case SENDING_FAILED: //resend request break; case OK: break; }
This is because I used Integer Type, then I changed the type to intand the problem is solved
Integer Type
int
My question is why we cannot use Integercase as an expression. The docs say, “The switch works with byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum types), the String class, and several special classes that wrap some primitive types: Character, Byte, Short, and Integer " , although the variable is constant. I read this question , but received nothing.
Integer
case switch ( §14.11) ( §5.2) .....
Definition of Constant Expression §15.28
, , .
, . Integer Expression .
"" : " , , char int . ( Enum), String , : , , "
switch(expressions used here)
case.
case
int case, Integer.valueOf(your_int_value);, Integer
Integer.valueOf(your_int_value);
java Object . byte, int, char . jdk1.7 String switch. Wraper Class valueOf -
private static final Integer INVALID_USER = 901; private static final Integer SENDING_FAILED = 902; private static final Integer OK = 903; /* * * And some more project related declaration... * */ switch (responseCode){ case INVALID_USER.valueOf(): // logout break; case SENDING_FAILED.valueOf(): //resend request break; case OK.valueOf(): break; }