What is Enum and how to use it properly?
While writing program there are times when we need to define a group of constants. In java, we can use Enum to define a group of constants. Enum came into the picture with JDK 1.5.
Features of enum
- It is a special data type like class and interface to define a group of constants;
- All the constants of enum are by default public static final
- Enum can have methods and constructor
- Enum can be declared inside or outside of a class
- We can use any type of value as enum constant value
- Enum internally extends Enum.class from java.lang package. As a result, enum can’t extend another class but it can implement interfaces.
Example of enum
Let’s say we need to define the constants for the weekdays. Rather than creating seven constant fields inside a class, we can declare an enum.
Output:
Weekday no 3
Use String as enum constant value
Output:
Weekday no Third Day
Enum methods
Enum class of java.lang package predefines some methods. For example compareTo(), toString(), valueOf()
compareTo() method
The compareTo() method is used to compares the constants of an enum. It compares the constant based on ordinal values.
toString() method
The toString() method converts the name of an enum to a string.
valueOf() method
The valueOf() method is a static method in the enum class and it is used to obtain an instance of the enum class for a given String value.
How to use enum properly?
Output:
setting up pre-prod env with url → https://preprod.com
Internal code generated when we declare an enum
For this Color enum internally compiler will generate below code