Using Integer in Switch Statement

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.

Leave a Comment