Monday, February 6, 2012

java enums tutorial: Best 10 examples of enum in java

Enums in java:-

Enum is one of the cool languages featured introduced as part of Java 5 version.
enum or enumeration values are constants meaning which can not be changed. These constants are specified using upper case letters as per java coding specifications

Enum is introduced in Java 5 version, Before Java 5 was introduced, we have to write our own constants to handle enum functionality as follows
public class MonthsConstants{
public static final String JAN="1";
public static final String FEB="2";
..
}
public class MonthsConstantsTest
{ int monthsCode; //can assign any value like 1,2 or 100
}

You have to handle all your constants yourself and causes error-prone.
These values are a valid type for compile time only and give an error if the wrong type is assigned to these values. Moreover, you can assign any values
if we want to add new constants, it would be more work is required for maintenance of your code. Because of all these enum class is introduced.

By default, enum implements java.lang.Enum which implements java.io.Serialization and java.lang.Comparable interfaces.

java enum API provides different methods like toString(),name() as well as valueOf() methods

I am listing down the best enum examples in java
1. How to define enum class?
This is one of the ways to define an enum in java
public enum Months{
JAN(1),FEB(2),MAR(3),APRIL(4),MAY(5),JUN(6),JUL(7),AUG(8),SEP(9),OCT(10),NOV(11),DEC(12);
}
This is going to create in a java class and enum class name. Please note that enum constants have a semicolon at the end of constant definition.

2.How to define enum in another class:-
public class MonthsClass{
public enum Months{
JAN(1),FEB(2),MAR(3),APRIL(4),MAY(5),JUN(6),JUL(7),AUG(8),SEP(9),OCT(10),NOV(11),DEC(12)
}
Months monthsNames;
}
In the above example, enum class is created in inside the class, please note that semicolon is not required after defining enum constants.

3. How to create an enum object?:-
MonthsClass monthsObject=new MonthsClass();
monthsObject.monthsNames=MonthsClass.Months.JAN;
we can create enum objects using the new operator. and also we can attach constants to the enum class
4. how to define enum constructor:-
public enum Months{
JAN(1),FEB(2),MAR(3),APRIL(4),MAY(5),JUN(6),JUL(7),AUG(8),SEP(9),OCT(10),NOV(11),DEC(12);
private int monthCode
Months(int monthCode){
this.monthCode=monthCode;
}
public int value(){
return monthCode;
}
enum constructor in enum are private, meaning outside classes should not able to create enum objects creation.

5. How to compare Enum objects in Java:-
normally we can compare objects using == and equals methods
enum constants can also be compared using the same.
if(Months.JAN==Months.FEB){return true else return false;}
we can also use the equals method to compare the enum objects of the same type.

6.iterate enum constants:-
enum class provides values() method for iteration which returns a list of enum constants in the order of constants creation.

for(Months months:Months.values()){
System.out.print(" "+months);
}
and output is:-
JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
7. How to convert enum to integer ?:-
We have encountered in our programming to convert enum constant to an integer.
As defined enum declaration in steps #4
Months months=Months.Jan;
Integer int=new Integer(months.value());
value method in enum provides the value for the enum constants.

8. How to convert an integer to an enum constant?:-
we have to define the following method in enum class for returning the Enum for the given input as an integer
static Months getMonths( int monthCode ) throws Exception
{
for (Months months : Months.values())
if (months.value() == monthCode)
return months;
}
Hope this solves the conversion to enum by providing an integer as input to the above method

9. How to convert String to enum object?
enum class provides valueOf(String )method to pass the string as an argument, which returns enum constants
Months month=Months.valueOf("JAN");
Months month=Months.valueOf("abc");
For the first line in the above code, month object prints the string value as Jan

second, the valid string is not passed to enum class, it throws java.lang.IllegalArgumentException with the message No enum constants for your class.

10.how to use enum class in switch condition:-

one of the coolest features of enum is we can use enum objects in switch case as like a primitive type
Months month=Months.JAN;
switch(month){
 case JAN:
  System.out.println("january");
  break;
 case FEB:
  System.out.println("febrauary");}
  break;
 ----
 ---
}

Advantages of Enum class:-

1. By default enum classes are implementing serialization, and overriding equals and hashcode methods so no need for explicit serialization implementation
2. With the usage of Enum class, EnumSet and EnumMap are introduced, a collection of enums operations can be achieved
3. Maintenance of code using enums is very easy

Disadvantages of Enum class:-
enum class is extending java.lang.Enum, the classes in java.lang are final so enum classes cannot be subclassed.

Hope you understand enum examples in java.

Please share your comments that how you are using the enum class in your development/

Related article