8/15/15

what is Enum in Java

Enums in Java


Enum type is a special data type. It allows user to create a variable which will have values from pre-defined constants. Enums are like class of constants and it works like singleton.

Example :-
Taking an example of months in year. Now you know months are 12 in a year, constant. So this enum will be

public enum Year {
          January, February, March, April, May, June, July, August, September, October, November,               December
}


Above enum can be used in a class like
Year.January;


You can also give these variables some constant values. Like in second example we will have enum of days in a week

public enum Week {
Monday((short)0), Tuesday((short)1), Wednesday((short)2), Thursday((short)3), Friday((short)4), Saturday((short)5), Sunday((short)6);

public final short key;

private Week(Short key) {
this.key = key;
}
public Short getKey() {
return key;
}
 }

In above example we have assigned a short value to each day in a week. This is helpful if you want to insert this value in database, as this will go as key and not text resulting in fast search.
Doing Week.Monday.getKey();
It will create Week object and set the key as you have defined. And calling of getKey will give you "0", which is key for Monday.

We can also use static to define constants but to use enum has advantage over static. Enums are "type-safe" while static are not.