The Power of Enum Types in Java: Examples and Use Case
In this article, we will discuss what is enum in java, how to implement it, important methods and three special cases of enum.
Table of Content
Best-suited Java courses for you
Learn Java with these high-rated online courses
What is enum in Java?
Enum is a special data type in java that represents a group of named constants. It is mainly used to define our own (pre-defined) data type.
Syntax
enum user_defined_name{constants ; // semicolon is optional}
Example: There are 12 months in a year, i.e. month is predefined. So, if we want to define month as a data type, then it can be defined as:
enum Month{
Jan, Feb, March, April, May, June, July, Aug, Sep, Oct, Nov, Dec;
}
Note:
- Predefined constants as anything that we know is fixed, like a week, seasons, days in a week, etc.
- In Java, whenever predefined constants are required, we should use an enum rather than code with the help of a class.
- Since an enum reduces lines of codes, hence complexity.
Must Check: What is Java?
Must Check: Top Java Online Courses & Certifications
Implementation of enum
Internally enum is represented using the class concept. Every enum constant is public static final, and every enum constant represents an object of the type enum. Let’s take an example to understand the object scenario.
enum Month{ class Month{ Jan, Feb; → public static final Jan j= new Jan(); } public static final Feb f = new Feb(); }
We can declare an enum inside and outside of class but not inside methods. Let’s see examples using a program to understand this scenario.
Declare enum outside class
Example: Show how to declare enum outside the class.
enum Season{ // declare enum type named constant Season outside class Winter,Spring , Summer , Monsoon , Autumn ; // semicolon is optional}
public class Main{ public static void main(String args[]) {
//access constant using enum type Season
Season season=Season.Monsoon;
//printing enum constant
System.out.println(season); }}
Output:
Monsoon
Note:
Public, default, and strictfp modifiers are allowed if we declare an enum outside of class.
Declare enum inside class
Example: Show how to declare enum inside the class.
public class Main{ enum Season{ // declare enum type named constant Season outside class Winter , Spring , Summer , Monsoon , Autumn ; // semicolon is optional } public static void main(String args[]) {
//access constant using enum type Season
Season season=Season.Monsoon;
//printing enum constant
System.out.println(season); }}
Output:
Monsoon
Note:
If we declare an enum inside a class, then public, default, private, protected, and static modifiers are allowed.
Important Methods in enum
values()
The main purpose of the values() method is to return an array of type enum to list out all the values or constants present inside the enum. Let’s see the below program to understand the Use of the values() method.
public class Main{
enum Season{ // declare enum type named constant Season outside class Winter , Spring , Summer , Monsoon , Autumn ; // semicolon is optional } public static void main(String args[]) {
//values method return array of type Season
Season[] seasons=Season.values();
//Use for each loop to print each season present inside seasons
for(Season season:seasons) {
//Printing each value or constant
System.out.println(season); } }}
Output:
Winter
Spring
Summer
Monsoon
Autumn
ordinal()
Within the enum order of constants are important, and we can represent this order by ordinal value. We can find the ordinal value of the enum constant by the ordinal() method. Ordinal values are 0-based array indexes. Indexing of constant inside an enum is an ordinal value. Let’s see the below program to understand it properly.
public class Main{ enum Season{ // declare enum type named constant Season outside class Winter, Spring, Summer, Monsoon, Autumn; // semicolon is optional } public static void main(String args[]) {
//values method return array of type Season
Season[] seasons=Season.values();
//Use for each loop to print each season present inside seasons
for(Season season:seasons) {
//Printing each value or constant with its ordinal value
System.out.println("enum constant is "+ season +" and ordinal value is "+season.ordinal()); } }}
Output:
enum constant is Winter and ordinal value is 0
enum constant is Spring and ordinal value is 1
enum constant is Summer and ordinal value is 2
enum constant is Monsoon and ordinal value is 3
enum constant is Autumn and ordinal value is 4
enum as Argument for Switch Statement
In Java, until the 1.4 version, only byte, short, char, and int are allowed as an argument for switch statements. From the 1.5 version, corresponding wrapper classes and enum types are also allowed as an argument for the switch statement. Let’s see the below program to understand how we can pass an enum type as an argument in the switch statement.
public class Main{ enum Season{ // declare enum type named constant Season outside class Winter , Spring , Summer , Monsoon , Autumn ; // semicolon is optional } public static void main(String args[]) { Season currSeason=Season.Summer; switch(currSeason) { case Winter: System.out.println("Low temperature...cold wweather"); break; case Spring: System.out.println("Not too cold Not little bit warm temperature"); break; case Summer: System.out.println("High temperature...Hot weather"); break; case Monsoon: System.out.println("Rainy season...must wear raincoat whenever go outside"); break; case Autumn: System.out.println("Not too warm Not too warm temperature"); break; } }}
Output
High temperature…Hot weather
Constructor inside Enum
Enum can contain a constructor, which is executed separately for every enum constant at the time of enum class loading. Every constant of an enum is an object of type enum. Since every constant is public static final and static variables are created at the time of class loading hence, the number of constants determines the number of times the constructor will execute. We can’t create an enum object explicitly, and hence we can’t invoke an enum constructor directly. Let’s see the below program and observe the output.
enum week{ Mon , Tue , Wed , Thu , Fri , Sat , Sun; // constants must be ending with semicolon // constructor week() { System.out.println("Constructor"); } } public class Main{ public static void main(String args[]) {
//access week day Tue using enum type week
week w=week.Tue; System.out.println("Ending"); } }
Output
Constructor
Constructor
Constructor
Constructor
Constructor
Constructor
Constructor
Ending
In the above program, even if we access one constant on an enum week but all the constants will be created, and hence, 7 times the constructor will execute since there is 7 constants in an enum week.
Inheritance with enum is not applicable
Every enum in Java is a direct child class of Java. lang. Enum class, so we cannot extend any other enum class. Every enum is always implicitly final; hence we cannot create a child enum. Because of these reasons, the Inheritance concept is not applicable to enums. Hence, we cannot use extends keywords for enums. But an enum can implement any number of interfaces simultaneously. It implements Serializable and Comparable interfaces.
Conclusion
In this article, we have briefly discussed enum in java, types of enum and its use cases wth the help of examples.
Hope, you like the article.
Contributed By: Shubham Kumar
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio