In Java, Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language. Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. The set of constants in an enum type doesn’t need to stay fixed for all time.
What is Enumeration or Enum in Java?
A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like classes, you can give them constructors, add instance variables and methods, and even implement interfaces.
Enum Example:
The 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.).
One thing to keep in mind is that, unlike classes, enumerations neither inherit other classes nor can get extended(i.e become superclass). We can also add variables, methods, and constructors to it. The main objective of an enum is to define our own data types(Enumerated Data Types).
Declaration of enum in Java
Enum declaration can be done outside a Class or inside a Class but not inside a Method.
1. Declaration outside the class
Java
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
|
2. Declaration inside a class
Java
public class Test {
enum Color {
RED,
GREEN,
BLUE;
}
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
|
- The first line inside the enum should be a list of constants and then other things like methods, variables, and constructors.
- According to Java naming conventions, it is recommended that we name constant with all capital letters
Properties of Enum in Java
There are certain properties followed by Enum as mentioned below:
- Every enum is internally implemented by using Class.
- Every enum constant represents an object of type enum.
- Enum type can be passed as an argument to switch statements.
- Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can’t create child enums.
- We can declare the main() method inside the enum. Hence we can invoke the enum directly from the Command Prompt.
Below is the implementation of the above properties:
Java
import java.util.Scanner;
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
public class Test {
Day day;
public Test(Day day) { this .day = day; }
public void dayIsLike()
{
switch (day) {
case MONDAY:
System.out.println( "Mondays are bad." );
break ;
case FRIDAY:
System.out.println( "Fridays are better." );
break ;
case SATURDAY:
case SUNDAY:
System.out.println( "Weekends are best." );
break ;
default :
System.out.println( "Midweek days are so-so." );
break ;
}
}
public static void main(String[] args)
{
String str = "MONDAY" ;
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}
|
Java Enum Programs
1. Main Function Inside Enum
We can declare a main function inside an enum as we can invoke the enum directly from the Command Prompt.
Below is the implementation of the above property:
Java
enum Color {
RED,
GREEN,
BLUE;
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
|
2. Loop through Enum
We can iterate over the Enum using values( ) and loop. values() function returns an array of Enum values as constants using which we can iterate over the values.
Below is the implementation of the loop through Enum:
Java
import java.io.*;
enum Color {
RED,
GREEN,
BLUE;
}
class GFG {
public static void main(String[] args)
{
for (Color var_1 : Color.values()) {
System.out.println(var_1);
}
}
}
|
3. Enum in a Switch Statement
Java
import java.io.*;
class GFG {
enum Color {
RED,
GREEN,
BLUE,
Yellow;
}
public static void main(String[] args)
{
Color var_1=Color.Yellow;
switch (var_1){
case RED:
System.out.println( "Red color observed" );
break ;
case GREEN:
System.out.println( "Green color observed" );
break ;
case BLUE:
System.out.println( "Blue color observed" );
default :
System.out.println( "Other color observed" );
}
}
}
|
OutputOther color observed
Enum and Inheritance
- All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, an enum cannot extend anything else.
- toString() method is overridden in java.lang.Enum class, which returns enum constant name.
- enum can implement many interfaces.
Enum and Constructor
- Enum can contain a constructor and it is executed separately for each enum constant at the time of the enum class loading.
- We can’t create enum objects explicitly and hence we can’t invoke the enum constructor directly.
Enum and Methods
Enum can contain both concrete methods and abstract methods. If an enum class has an abstract method, then each instance of the enum class must implement it.
Java
enum Color {
RED,
GREEN,
BLUE;
private Color()
{
System.out.println( "Constructor called for : "
+ this .toString());
}
public void colorInfo()
{
System.out.println( "Universal Color" );
}
}
public class Test {
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}
}
|
OutputConstructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color
FAQs on Enum in Java
Q1. Can we create the instance of Enum by the new keyword?
Ans:
No, we can’t create the instance of the Enum keyword because it contains private constructors only.
Q2. Can we have an abstract method in the Enum?
Ans:
Yes, we have an abstract method in Enum.
Q3. What is the purpose of the values() method in the enum?
Ans:
In Java, the values( ) method can be used to return all values present inside the enum.
Q4. What is the purpose of the valueOf() method in the enum?
Ans:
The valueOf() method returns the enum constant of the specified string value if exists.
Q5. What is the purpose of the ordinal() method in the enum?
Ans:
By using the ordinal() method, each enum constant index can be found, just like an array index.
Q6. Write a program in Java to describe the use of values(), valueOf(), and ordinal() methods in the enum.
Ans:
Java
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
public static void main(String[] args)
{
Color arr[] = Color.values();
for (Color col : arr) {
System.out.println(col + " at index "
+ col.ordinal());
}
System.out.println(Color.valueOf( "RED" ));
}
}
|
OutputRED at index 0
GREEN at index 1
BLUE at index 2
RED
Next Article on enum: Enum with Customized Value in Java
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.