Java Enum, short for Enumeration in Java, is a powerful and versatile feature introduced in Java JDK 5 that allows developers or automation testers to define a set of named constants. Enums provide a convenient way to represent a fixed set of values, enhancing Java code’s clarity, readability, and maintainability.
Throughout this Enumeration in Java tutorial, we will learn how to create an Enum while exploring the advantages of utilizing Enumeration in Java, examining the various features of enum types, understanding their implementation Enumeration in Java programming, and recognizing situations where using enums might not be appropriate.
Additionally, we will gain practical knowledge by exploring examples of working with Java Enum’s valueOf(), enum values(), EnumSet, and EnumMap.
Enumeration in Java Basics
Enumerations generally represent a collection of related constants and have been present in programming languages like C++ since their inception. In Java, the decision to incorporate this feature came after JDK 1.4, and it was officially introduced in the JDK 1.5 release.
In Java, enumerations are implemented using the “enum” keyword. They are considered a specialized type of class, consistently extending the “java.lang.Enum” class.
What is Enumeration in Java?
Enumeration refers to a collection of named constants. In Java, an enumeration defines a class type that can include constructors, methods, and instance variables. It is created by using the “enum” keyword. By default, Each enumeration constant is public, static, and final. Although enumerations define a class type and can have constructors, you can not be instantiated by using the “new” keyword. But you can use and declare the Java Enumeration variables as you do for a primitive variable.
Let’s dive deeper into Enumeration and explore its syntax and declaration.
How to Define Enumeration in Java?
The declaration of an enum can be performed outside or within a class, accompanied by a list of enum variables. However, it is not permissible to declare an enum inside a method. To better understand the declaration process, let’s take an example.
Program: Enum Outside Class Example
Let us start with an example where we will declare an enum outside a class.
package com.softwaretestingo.enumeration; //To declare enum keyword is used instead of class keyword enum Direction { NORTH, SOUTH, EAST, WEST; } public class EnumDeclarationEx1 { public static void main(String[] args) { // For Creating referenceno need of New Keyword Direction dr=Direction.EAST; System.out.println("Direction is: "+dr); } }
Output:
Direction is: EAST
Program: Enum Inside Class Example
Now, we will see how to declare the same Direction enum inside a class.
package com.softwaretestingo.enumeration; public class EnumDeclarationEx2 { //To declare enum keyword is used instead of class keyword enum Directions { NORTH, SOUTH, EAST, WEST; } public static void main(String[] args) { // For Creating referenceno need of New Keyword Directions dr=Directions.WEST; System.out.println("Direction is: "+dr); } }
Output:
Direction is: WEST
- In an enum, the first line should have all the constants that you want to use in your program. After that, you can add the variables and methods.
- Enum names should be declared the same as the class name, but as the enums are CONSTANT and in Java, constants are written in Capital letters, we have to follow the same for enums.
- Enumeration constants, by default, are public, static, and final.
- We can directly define the variables of the Enumeration in Java without using the new keyword.
- Enum improves type safety, and also, we can easily traverse.
- While using Enum, you can implement many interfaces but can not extend any classes because it internally extends the Enum class.
Program: Example of Enum Java With If Else
package com.softwaretestingo.enumeration; public class EnumWithIfElseEx { enum WeekDays { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public static void main(String[] args) { WeekDays weekDays = WeekDays.WEDNESDAY; if(weekDays == WeekDays.SUNDAY || weekDays == WeekDays.SATURDAY) System.out.println("It is Weekend"); else System.out.println("It is weekday: "+weekDays); } }
Output:
It is weekday: WEDNESDAY
Program: Enum Java With Switch statement
You can use the values of an enumeration to control a switch statement. However, it’s important to remember that all the case statements within the switch statement should only use constants from the same enumeration.
package com.softwaretestingo.enumeration; enum AllDirections { NORTH, SOUTH, EAST, WEST } public class EnumWithSwitchCaseEx { public static void main(String[] args) { AllDirections adr=AllDirections.SOUTH; switch(adr) { // You can use the constants which are declared inside the Enum case NORTH: System.out.println("North direction"); break; case SOUTH: System.out.println("South direction"); break; case EAST: System.out.println("East directiion"); break; case WEST: System.out.println("West directiion"); break; } } }
Output:
South direction
After going through this program, we believe you can use Enum Java with the switch case statement. Now let’s understand a few other methods of enum like Values( ) and ValueOf( ) and will understand the difference between them.
Values( ) and ValueOf( ) Method
Values(): The Java compiler automatically generates the values () method when creating an enum. It will return an array of enum types that hold all the enum’s values or constants.
The syntax for the values() method is
public static enum-type[ ] values()
Let’s take an example of how to use the values() method in your Java program:
Program: Get All the Constant Values of Enum
package com.softwaretestingo.enumeration; public class EnumValuesMethodUseEx { enum Days { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY } public static void main(String[] args) { System.out.println("Here are the All Days Name"); // This will return all the constants as an array of days Enum Days day[]=Days.values(); for (Days d: day) { System.out.println(d); } } }
Output:
Here are the All Days Name SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
ValueOf(): The purpose of this ValueOf() method is to retrieve the enumeration constant that matches the value of the string provided as an argument when invoking the method. And the syntax for the Java enum ValueOf() method is below:
public static enum-type valueOf (String str)
Now, we will go through an example to better understand the valueOf() method
Program: Get Specific Constant Values of Enum
package com.softwaretestingo.enumeration; public class EnumValueOfMethodUseEx { enum Days { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY } public static void main(String[] args) { Days d; d=Days.valueOf("FRIDAY"); System.out.println(d); } }
Output:
FRIDAY
The valueOf() method is case-sensitive. If you enter a value not available in the Enum, you will get the below error message.
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.softwaretestingo.enumeration.EnumValueOfMethodUseEx.Days.FRIDAY1 at java.base/java.lang.Enum.valueOf(Enum.java:273) at com.softwaretestingo.enumeration.EnumValueOfMethodUseEx$Days.valueOf(EnumValueOfMethodUseEx.java:1) at com.softwaretestingo.enumeration.EnumValueOfMethodUseEx.main(EnumValueOfMethodUseEx.java:12)
As you can see, we don’t have any constants like “FRIDAY1”; that’s why we are receiving the IllegalArgumentException.
You can use the Values() method to get an array containing all the enum elements and the ValueOf() method to retrieve a specific enum constant. I hope you understand this idea. Now, let’s continue and learn about the implementation of Enumeration in Java, including the constructor, instance variables, and methods.
Use Of Methods, Constructors, and VariablesWith Enum java
Enumeration is like a class, but you can’t create objects from it. It can have methods, constructors, and variables. In this example, we are making a constructor and a method in the enum and using them to access its constant values.
Program: Use Of Constructor, Method & Variable In Enum
package com.softwaretestingo.enumeration; public class EnumWithConstructorVariableMethodEx { enum colors { RED(10),BLUE(20),GREEN(30),ORANGE(40); // variables private int colorcode; //method private int getColorCode() { return colorcode; } //Constructor colors(int colorcode) { this.colorcode=colorcode; } } public static void main(String[] args) { colors cr; System.out.println("Colorcode Of Green is : "+colors.GREEN.getColorCode()); } }
Output:
Colorcode Of Green is : 30
The example above automatically invokes the constructor once we declare an enum variable (colors cr). It initializes the colorcode parameter for each enumeration constant with the specified values provided in parentheses. That’s how it functions.
When is using enums considered a bad idea?
Experts often discourage the usage of enums, considering it a problematic coding practice. The primary concern is that enums result in excessive switch-case or if-else statements scattered across the program. This goes against maintaining a single responsibility for each code section. Whenever changes are made to an enum declaration, updating the corresponding code in multiple places becomes necessary. Neglecting to update all instances can potentially introduce bugs into the program.
Conclusion:
Congratulations! You have reached the conclusion of this article about Enumeration in Java. I sincerely hope you found the information presented in this article informative and valuable. By delving into the concept of Enumeration, we have explored its features, applications, and potential benefits in Java programming.
I trust that you have better understood how Enumeration works and how it can be utilized effectively in your projects. Thank you for joining me on this journey of learning, and I hope you found this article to be a helpful resource.