Java Enums with Example

Java enum type is a special type of class for creating a collection of constants.

Please note that enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.

enum keyword is used for creating an enum.

enum LogLevel {

ERROR, WARN, INFO, DEBUG;

}

Enum valueOf

The valueOf() method can be used to obtain an instance of the enum class for a given String value.

LogLevel level = LogLevel.valueOf(“ERROR”);

Enum values are compared using ==

LogLevel level = LogLevel.valueOf(“ERROR”);

if(level == LogLevel.ERROR){

System.out.println(“It is an error log”); 

}

We can define constructor , fields and methods for an enum just like normal classes. Please note that the constructor of enum can only be private and enum constants can only be created inside Enums itself.

 

Let us look into the below codes for better understanding of enum.

Enum with constructor and method

E14

Output

O14

ordinal() method returns the order of an enum instance.

values() method returns an array of Enum values. In the below example, Fruit.values() returns the array of enums defined in Fruit.

Enum with instance variable

E15

Output

Screen Shot 2020-01-29 at 8.20.17 PM

Enum in switch

Screen Shot 2020-01-29 at 8.22.26 PM

Output

Screen Shot 2020-01-29 at 8.24.01 PM

Leave a Reply

Your email address will not be published. Required fields are marked *