{

java enumeration tutorial: Best 10 examples of enum constants in java


This tutorial explains Enumeration in java with examples.

What is Enum in java

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

create arraylist from array in java with example

Enum is introduced in Java 5 version, Before Java 5 was introduced, we have to write our constants to handle enum functionality as follows.

Enum can have a string of values or integer only.

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 required for the maintenance of your code. Because of all these, the enum class is introduced.

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

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

I am listing down the best enum examples in java

How to define enum class?

Enum declares with the enum keyword. These are defined in a separate file or existing java classes.

If you define the enum class as public, Declaration should be in a separate java file.

It 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);  
}  

We are going to create this in a java class file and enum class name.

Please note that enum constants have a semicolon at the end of the constant definition.

  • Defined Months Enum class
  • Each Enum constant contains String and integer value to it

How to define enum in another class?

It is an example of an enum declaration in other classes.

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, the enum class is created inside the Months Class. This approach does not require adding a semicolon at end of enum constants.

How to create an enum object?

we create enum objects using the new operator. and also we can attach constants to the enum class.

Here is an example for creating an object for enum class

MonthsClass monthsObject=new MonthsClass();  
monthsObject.monthsNames=MonthsClass.Months.JAN;  

How to define enum constructor?

Enum declarations are similar to a class, So Enum can have a constructor. It is called during enum object creation.

Constructors in an enum are private, meaning outside classes should not able to create enum objects creation.

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;  
}  

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 approach.

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.

How to iterate enum constants

enum class provides the values() method for iteration that returns a list of enum constants in the order of constants creation.

for(Months months:Months.values()){  
System.out.print(" "+months);  
}  

output:

JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC  

How to convert enum to integer?

Sometimes, You want to convert the enum constant to an integer.
As defined enum declaration in above

Months months=Months.Jan;  
Integer int=new Integer(months.value());  

value method in enum provides the value of the enum constants.

How to convert an integer to an enum constant?

we have to define the following method in 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

How to convert String to enum object?

enum class provides valueOf() method to pass the string as an argument, which returns enum constants

Months month=Months.valueOf("JAN");  
Months month=Months.valueOf("abc");  

The first line in the above code, month object prints the string value as Jan

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

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;  
 ----  
 ---  
}  

Enum class Advantages in java

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

Enum class Disadvantages

enum class is extending java.lang.Enum, the classes in java.lang are final so enum classes cannot be sub-classed.

Hope you understand enum examples in java.

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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.