Why Java enums?

In Java, enum was introduced to replace the use of int constants. Suppose we have used a collection of int constants.


\begin{lstlisting}
class Size {
public final static int SMALL = 1;
public fina...
...tatic int LARGE = 3;
public final static int EXTRALARGE = 4;
}
\end{lstlisting}

Here, the problem arises if we print the constants. It is because only the number is printed which might not be helpful. So, instead of using int constants, we can simply use enums. For example,


\begin{lstlisting}
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
\end{lstlisting}

This makes our code more intuitive. Also, enum provides compile-time type safety. If we declare a variable of the Size type (like in the above examples), it is guaranteed that the variable will hold one of the four values. If we try to pass values other than those four values, the compiler will generate an error.