Java: Enum vs. Int

Both ints and enums can use both switch or if-then-else, and memory usage is also minimal for both, and speed is similar – there’s no significant difference between them on the points you raised.

However, the most important difference is the type checking. Enums are checked, ints are not.

Consider this code:

public class SomeClass {
    public static int RED = 1;
    public static int BLUE = 2;
    public static int YELLOW = 3;
    public static int GREEN = 3; // sic

    private int color;

    public void setColor(int color) {
        this.color = color;
    }   
}

While many clients will use this properly,

new SomeClass().setColor(SomeClass.RED);

There is nothing stopping them from writing this:

new SomeClass().setColor(999);

There are three main problems with using the public static final pattern:

  • The problem occurs at runtime, not compile time, so it’s going to be more expensive to fix, and harder to find the cause
  • You have to write code to handle bad input – typically a if-then-else with a final else throw new IllegalArgumentException("Unknown color " + color); – again expensive
  • There is nothing preventing a collision of constants – the above class code will compile even though YELLOW and GREEN both have the same value 3

If you use enums, you address all these problems:

  • Your code won’t compile unless you pass valid values in
  • No need for any special “bad input” code – the compiler handles that for you
  • Enum values are unique

Leave a Comment