Published in


[JAVA] History of Enum

Image: https://twitter.com/java?lang=es

What is Enum?

An enum type, introduced in Java 5, is a special data type that enables a variable to be a set of predefined constants. It is often used when we know all the possible values at compile time while the set of constants can be modified whenever we need them.

History of Enum

Until the enum type was presented, Java developers used to define constants with extra comments:

In this code, Monday should be fixed at 1, Tuesday at 2, and Wednesday at 3. As this rule is set on a comment, it would be a problem to divide the comment and the code or to delete one of them, especially the comment. We can improve it if we get to know the meaning of the numbers by their own name.

Now each number has its own name that we can easily figure out so that the switch statement becomes more straightforward. Also, the variables become constant by the final keyword and are assigned only once on memory by the static keyword. Note that we can better source code in using an interface as this shape of code ( private final static ) can be left out in it:

Looks way better, doesn’t it? Nonetheless, it has one trivial problem, where it cannot guarantee compile-time safety when you try comparing two different sets of constants like:

if (Day.Monday == Month.January) {
System.out.println("Mondays are bad");

If the Java compiler doesn't find that kind of source code and doesn’t mark it as an error, you might have an unexpected error in runtime. To get rid of the risk, one smart Java developer might suggest a way to change the interfaces to classes and to make the data type of each constant to neither int nor other things but to its class so that an instance of their class would be assigned to every single of them. If then, it’s certain that the compiler finds the error as Day.Monday and Month.January belong to different data types. But one constraint still remains in this amazing method that you cannot use the switch statement any longer because it does not support customized data types. Boom! Here is the reason why an enum type has been presented from Java 5.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Minho Jang

Minho Jang

Backend Developer, Writer, and Lifelong Learner