For various business reasons I want to hold some static IDs in one of my classes. They were originally int
but I wanted to change them to Integer
s
Switch require constant expressions in the case
statements or enum constants. A constant expression is:
an expression denoting a value of primitive type or a String that does not complete abruptly
So Integers don't qualify. In your case, you can either use an int
or an enum (which would make sense if your IDs are known at compile time).
The only place where you can use a boxed type (for example an Integer) is in the switch expression:
switch(Integer.valueOf(1)) {
case 1: //
}
In the code shown 'i' is an object pointer, not a constant expression.
because I was looking at this...
The accepted answer says that:
switch can only work with primitives, enum values and (since Java 7) strings
However,
14.11 The switch Statement
outlines the JavaSE7 documentation for switch that shows:
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.
I just wanted to clarify for future surfers.
Now that java offers enums, we usually do it like this :
public enum MyKey {
i,
j
}
...
switch(mObj.getId()){
case i: //do something
default: //do something default
}
Change your constant to primitive type:
private static final int i = 1;
and you'll be fine. switch
can only work with primitives, enum values and (since Java 7) strings. Few tips:
new Integer(myint).equals(...)
might be superflous. If at least one of the variables is primitive, just do: myint == ...
. equals()
is only needed when comparing to Integer
wrappers.
Prefer Integer.valueOf(myInt)
instead of new Integer(myInt)
- and rely on autoboxing whenever possible.
Constant are typically written using capital case in Java, so static final int I = 1
.
You must use a constant value in a switch statement.
switch(mObj.getId()){
case 5: //do something
default: //do something default
}