Java Enum
In java, we have a special type of class called enum
, which is used to represent the set of constants.
The keywork enum
is used to create an enum
.
Syntax for creating enum
enum EnumName {
// set of constants seperated by comma.
}
Example
enum Priority {
LOW,
MEDIUM,
HIGH
}
The constant values should be always in uppercase.
In the above code, we have created an enum
variable named Priority
with constant value LOW
,MEDIUM
and HIGH
.
To access the value of Priority
enum we use the following code.
Priority level= Priority.MEDIUM;
Example program for Enum
enum Priority {
LOW,
MEDIUM,
HIGH
}
public class Main {
public static void main(String[] args) {
Priority taskPriority = Priority.HIGH;
System.out.println("Task Status:");
switch(taskPriority) {
case LOW:
System.out.println("Task is of low priority.");
break;
case MEDIUM:
System.out.println("Task is of medium priority");
break;
case HIGH:
System.out.println("High priority task. Do it first");
break;
}
}
}
Output
Task Status:
High priority task. Do it first
In the above program, we have created an enum
with name Priority
with set of values.
In the Main
class, we have a enum variable of type Priority
with the value Priority.HIGH
.
Next, we check the values of it using switch
statement and print the values accordingly.
Looping through Enum
It is also possible to loop through the enum
values using values()
method. Calling this function will return all the constant values of the enum.
Example to loop enum variable
enum Priority {
LOW,
MEDIUM,
HIGH
}
public class Main
{
public static void main(String[] args) {
for (Priority level : Priority.values()) {
System.out.println(level);
}
}
}
Output
LOW
MEDIUM
HIGH