A Java Enum is a special data type, Where this data type has a group of predefined constants variables. A Variable has a predefined value (unchangeable variables, like final variables). For example A days in a week – Mon, Tus…etc. The direction in earth North, East, West, and South. That both are predefined equal value for variables.
It’s used when you want a represent a fixed set of constants. For example flags in the program or menu etc.
Java enums are added in Java 5 and its full form is java enumeration. In this tutorial, you will learn what is Java enum and how to create it with the use of it.
Java Enum example
As a class enum just need to use “enum keyword” before the name Enum Class in Java.
There is some guidance for constant – It should be written as uppercase letters, So enum type’s fields also uppercase letters. Check the below enum class example.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
To access enum
constants use the dot syntax with it:
Day myDay = Day.FRIDAY;
Complete code:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } class Hello { public static void main(String[] args) { Day myDay = Day.FRIDAY; System.out.println(myDay); } }
Output: FRIDAY
Enum string (toString)
It’s important some time needs to Java Enum String. You can do it with use toString() methods. Here is an example code.
Day myDay = Day.FRIDAY; System.out.println(myDay.toString());
Enum in a Switch Statement
To check for corresponding values, you can use Enumeration in a Switch Statement.
enum Speed { LOW, MEDIUM, HIGH } class Hello { public static void main(String[] args) { Speed mySpeed = Speed.MEDIUM; switch(mySpeed) { case LOW: System.out.println("Low Speed"); break; case MEDIUM: System.out.println("Medium Speed"); break; case HIGH: System.out.println("High Speed"); break; } } }
Output: Medium Speed
Loop Through an Enum
The Java enum methods – A values() method, which returns an array of all enum constants. This method is useful if you want to loop through the constants of an enum same as below example.
enum Speed { LOW, MEDIUM, HIGH } class Hello { public static void main(String[] args) { for (Speed mySpeed : Speed.values()) { System.out.println(mySpeed); } } }
Output: LOW
MEDIUM
HIGH
Enum int & Java enum key value
You seen the above Enum String now may you have a question is possible to convert Java Enum in int or creating Enum int?
Need to create a public final varible and private constructor same as below example. Where every content has a value (key-value pair) of it.
enum Speed { LOW(10), MEDIUM(50), HIGH(100); public final int value; private Speed(int value) { this.value = value; } } class Hello { public static void main(String[] args) { Speed mySpeed = Speed.LOW; System.out.println(mySpeed.value); } }
Output: 10
Unique Number Enum Ordinal
If you want a unique number that represents the enum value, you can use ordinal()
.
enum Color { White, Green, Blue, Purple, Orange, Red } class Hello { public static void main(String[] args) { //cast enum to int int color = Color.Blue.ordinal(); System.out.println(color); } }
Output: 2
Java Enum Constructor
The constructor for an enum type must be private access (package-private). It will automatically create a constant as defined at the beginning of the enum class body. But you can’t invoke an enum constructor yourself, check the below example.
enum Apple { A(100), B(190), C(120); private int price; // price of each apple // Constructor Apple(int p) { price = p; } int getPrice() { return price; } } public class Fruits { public static void main(String args[]) { Apple ap; // Print price of Apple A. System.out.println(Apple.A.getPrice()); // Display all apples and prices. System.out.println("All apple prices:"); for (Apple a : Apple.values()) System.out.println(a + " costs " + a.getPrice()); } }
Output: 100
All apple prices:
A costs 100
B costs 190
C costs 120
Enum Methods in Java
A some methods of enum are values(), ordinal() and valueOf() methods. Here are a complete example and use of all methods.
enum Color { WHITE, BLACK, BLUE; } public class Hello { public static void main(String[] args) { // Calling values() Color arr[] = Color.values(); // enum with loop for (Color col : arr) { // Calling ordinal() to find index // of color. System.out.println(col + " at index " + col.ordinal()); } System.out.println(Color.valueOf("WHITE")); } }
Output: WHITE at index 0
BLACK at index 1
BLUE at index 2
WHITE
Important Points to Remember for Java Enum
- Enum can implement an interface but can’t extend a class, because it’s internally extending an Enum Class.
- It can have fields (variables etc), constructors, and methods.
- An Enum can be traversed.
- Improves type safety.
- Easily used in control statement like a switch statement.
Question: What is the Difference between Enums and Classes?
Answer: A Java enum can just like a Java class but with some restrictions like Enum can’t be overridden methods. It also has variables and methods but all constant.
An enum is not used to create an object and can’t extend classes but can implement interfaces. An implement interface is the same as does in classes.
Question: Why and where use Java Enums?
Answer: Use it where variables will not change like days of the week.
Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1Java version 11
All Java Enumeration Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.