Java Enum Introduction
An Enumeration is a list of named constants. We can create constants in Java using final and static keywords as well. But whenever we want a variable to hold a value from a set of valid values, enumerations can be used and has advantage over constants created using final keyword.
Consider a pizza ordering application where the pizza sizes are represented as constants as follows.
public static final int SMALL = 1; public static final int MEDIUM = 2; public static final int LARGE = 3;
And in some part of the code, we may check some conditions like,
if(pizzaSize == SMALL) makeSmallPizza(); else if(pizzaSize == MEDIUM) makeMediumPizza(); else if(pizzaSize == LARGE) makeLargePizza();
where, value of pizzaSize is set in some part of code. If the ‘pizzaSize’ variable is set a value other than 1, 2 or 3 – which is possible because ‘pizzaSize’ is nothing but an int variable so we can set it to any value in integer range – the code may not go wrong as we expect. This is where enums (enumerations) come to the rescue.
Before we say how enum solves this problem of assigning bad/illegal values, we will see how to define and use an enum.