To define enumeration in dictionary word it’s a collection of stuff/things we put them together, like if we create a enumeration for months of the year this would be set of data as month names, In java we declare enumeration like we declare class but with more specific key name like enum.

package com.dbdiary.clean;

public enum Months {

January, februray,
march, april, may, june,
july, august, september, october


As you can see in example above, we have names of the month all in one enumeration class and we can access that from other classes by only mentioned the class name followed by enumeration name.

Why we should Enumeration?

If we use enumeration we will be having a type safety what I mean by that is for example often programmers name something and later on they forget the exact name they created this will cause programmers to compare two string with different spelling or different capitalization which will fail as in most of programming language they are case sensitive like in java, to solve this we can use enumeration to have same spelling even same capitalization without even retyping that String we created over and over again in our program.

And also in enumeration we can group things together like we have a group of months name, or group of animals in one enumeration or even we can create sets of objects that are in the same category where latter in our program we can use them and refer them as group followed by the name of enumeration.

In example bellow I have created enumeration named Months inside that I have included name of the months in a year in left, and in the right I have created another class to access and work with those list of months I grouped in one enumeration, to access them all I need is to give the name of enumeration followed by a DOT (.) it populated Months name which I declared in enumeration class.

enumeration example in java enumeration example in java

And lastly as enumeration are list of similar types of data like if you put String then you have to include other list as String as well or if it’s Integer all of them should be integer, if the data type are similar then we can iterate the enumeration easily in java like we can loop through the list easily as we do normally we arrays.

When to use Enumeration?

A lot of the time there is confusion in why to use enumeration where we can find other ways to do the same thing but I recommend you should use where ever you feel like you can use them because it constraint your input in a lot of ways.

A good example would be use it whenever you use any String as a constant in your program, so in place of Constant String use enumeration because you might do comparison with String and a lot of time there is typo in comparing String and if you use enumeration then you feel safe by not making any typo mistakes.