Enums in Java are a way to group constant values together, like days of the week, colors, or directions. Instead of using plain strings or numbers, enums make your code cleaner, safer, and easier to understand. They were added in Java 5 and come with powerful features like methods, constructors, and the ability to use them in switch statements. You can even loop through them or use them in special collections like EnumSet and EnumMap.
This article provides an in-depth overview of enums in Java.
Table of Contents:
What is Enum in Java?
An enum in Java (or enumeration) is a special type of class that is used to define a group of constants whose values don’t change. The constants are the objects of the enum type, which were introduced in Java 5 as a part of the Java type system. Enums are not instantiated with the new keyword, and they neither inherit from other classes nor extend other classes. They can be given constructors and methods, and can be implemented by an interface.
For example, days of the week, directions (NORTH, SOUTH), traffic lights (RED, GREEN, YELLOW).
Enums are mainly used when
- All possible values are known in advance
- Meaningful names are needed for the class
- You want to avoid mistakes like typos, e.g., writing “monday” instead of “Monday”.
Syntax:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
Properties of Enum in Java
1. Enums are reference types just like classes and interfaces. Enums are reference types, similar to classes. When you create an enum, you’re working with a reference to an object in memory.
2. Each constant in an enum is a public, static, and final object. When a constant is defined in an enum, it becomes a public, static, and final field.
3. Enums can have constructors, fields, methods, and even implement interfaces. In the below example, a constructor(Color(String type) { this.type = type; }) of the class Color is made, and a method is also defined to perform calculations.
enum Color {
RED("Warm"), BLUE("Cool");
private String type;
Color(String type) { this.type = type; }
public String getType() { return type; }
}
4. Enums cannot extend other classes because they implicitly extend java.lang.Enum. In Java, every enum already extends a special class called java.lang.Enum and multiple inheritance are not supported in Java.
5. Enum constants are implicitly static and final. You cannot change the values of the enum once it is defined, which prevents bugs and typo errors. In the below example, the constants NORTH and SOUTH are once created, cannot be reassigned.
enum Direction {
NORTH, SOUTH;
}
Declaration of an Enum in Java
In Java, you use the enum keyword outside the class, inside the class, with methods, fields, and with the switch statement. Let us discuss it in detail.
1. Declaration Outside the Class
An enum in Java can be declared outside the class to make the class accessible to multiple classes in the same package, and you can also add methods, constructors, and fields to it. It is useful when the enum is a core part of the program, not just for internal use inside one class.
Example:
Output:
Explanation:
In the Java code, the enum Direction is defined outside the class Example, which is like creating a separate class. The enum Direction has 4 constants, NORTH, SOUTH, EAST, WEST, and then Direction.NORTH is printed.
2. Declaration of an Enum inside a Class
An enum in Java is declared inside the class when it is only needed inside that class, which keeps the code neat, organized, and also shows that the enum is a logical part of the class’s functionality. Inside the class, you can also control the access of the enum, i.e., it can be marked as private, protected, or public based on how much you want to expose it.
Example:
Output:
Explanation:
In the above Java program, the enum direction is declared inside the class Example. Here, it is nested inside the class, so it is only available within this class or by the class name.
In the above example, you can also access the enum from outside the class by,
Example.Direction d = Example.Direction.NORTH;
Where the Example is the name of the Class, Direction is the name of the enum, and NORTH is the constant value in the enum.
3. Enum with Fields and Methods in Java
An enum in Java can be declared with fields and methods to associate additional information with each enum constant (like a label, code, price, etc.). It also allows enum constants to behave like objects, and this allows each enum constant to encapsulate custom behavior, such as formatting, filtering, or decision-making logic.
Example:
Output:
Explanation:
In the above Java program, the enum Color has three constants RED, GREEN, and BLUE. The field mood is a variable inside the enum to store extra data for each constant, and the method getMood returns the mood of each color.
4. Enum with Constructor
In Java, enums can have constructors, just like classes, to add more meaning to each constant, like a number, string, or other value. It also gives object-like behaviour to the constants, keeping them type safe. Enum constructors must have private or default accessors, you cannot use public or protected with enum constructors, and they cannot be created with the new keyword. They are created only once when the class is loaded.
Example:
Output:
Explanation:
In the above Java program, the enum Color has constants with arguments, which pass a string to the constructor. The constructor Color(String) runs once per constant and stores the passed value (“Warm”, “Peaceful”, etc.) in the mood field.
5. Enum with an Interface
An enum in Java can be implemented by one or more interfaces, just like a class, which makes it more powerful because you can make them follow a set of methods defined by an interface. Each enum constant can have its own implementation of the interface methods, like an anonymous class. It also gives compile-time safety to the program.
Example:
Output:
Explanation:
The above example has an interface Operation, which has a method apply(). The class MathOperation is implemented by the interface Operation, and every method provides its own implementation of that method.
Get 100% Hike!
Master Most in Demand Skills Now!
6. Enum with Abstract Methods
An enum in Java can be defined by a common abstract method in the enum, and then give each constant its own specific implementation of that method. Abstract method with an enum is used when each constant of an enum has to behave differently, i.e., each constant has its own behaviour.
Example:
Output:
Explanation:
The above Java program has an abstract method apply(), which is implemented by all the constants present in the enum Operation. Further, the enum Operation is called with its parameter arguments.
Enum and Inheritance
An enum in Java cannot extend another class because every enum already implicitly extends the class java.lang.Enum. Java uses single inheritance, i.e., a single class can extend only one class. But an Enum can implement multiple interfaces, as we have discussed above.
Example:
Output:
Explanation:
In the above Java program, the MyEnum enum is used is extend the BaseClass, which is not permitted because the enum by default extends the class java.lang.Enum.
Java Enum Programs
Below, we have discussed some practical Java enum programs that demonstrate how to define, loop through, and use enums in switch statements. Each example is simple and ready to run.
1. Main Function Inside the Enum
You can write the main() method directly inside the enum, which is useful when you are testing the behavior of the enum. It is a similar way to you use a class inside a main() method.
Example:
Output:
Explanation:
In the above Java example, the enum Color has 3 constants, RED, GREEN, and BLUE. Then, the main method is made inside the Color enumeration.
2. Loop Through the Enum
If you want to display all the constants defined in an enum, Java provides a built-in method called values(), which returns an array of all enum constants.
Example:
Output:
Explanation:
In the above Java program, the Level.values() is used to iterate through all the constants present in the enum.
3. Using Enum in Switch Statements
An enum can be used with the switch statements to make the switch cases easier to read and understand compared to using plain strings or numbers. Inside the switch statement, you only have to write the CONSTANT name, not the class.CONSTANT.
Example:
Output:
Explanation:
In the above Java program, the enum Day is defined with 7 constants, one for each day of the week. A variable today is created and assigned the value Day.WEDNESDAY, which is then used in the switch statement to determine the corresponding message..
EnumSet
EnumSet is a Set implementation in Java that is designed to work only with enum types, and is part of the java.util package was introduced in Java 5 with the enums.
EnumSet is widely used because
- Faster than HashSet: It uses bitwise operations internally, and every enum constant has a bit position. When you add or check an element, it assigns bits directly, instead of using hashing like HashSet, hence no need to compute hash code and no collisions.
- Type-safe: EnumSet is a generic class and requires a specific enum type. If you try to add anything that is not part of the enum, the code will not compile.
- Clean Code: You don’t have to create a Set manually and add elements one by one, instead, you can use methods like EnumSet.of() and EnumSet.range(), which are clear, expressive, and concise.
Example:
Output:
Explanation:
In the above Java program, the enum Day has 7 constants. In the main method, the EnumSet<Day> weekdays creates an EnumSet of the type Day. The method EnumSet.range() iterates from the starting till the end, and then it is printed.
EnumMap
EnumMap is a special kind of Map in Java that is designed to work only with enum keys. It is part of java.util package and was introduced in Java 5, alongside enums. EnumMap is widely used because
- Faster and Lighter Than HashMap: EnumMap uses hashing for keys, and computes hash codes and handles collisions. Internally, it uses an array of values where the index of the array corresponds to the enum constant.
- Preserves the Natural Order of Enum Constants: EnumMap maintains the order in which the enum constants are declared, so when you iterate through it, the keys come out in the same order as the enum.
- Type-Safe: EnumMap can only use one specific enum type as keys, so you will never insert the wrong type, and it makes your code easy to understand.
Example:
Output:
Explanation:
In the above Java program, the enum Day is created with 7 constants. In the main method, the EnumMap<Day, String> creates an empty EnumMap named Maps, and the values are further added to it.
Unlock Your Future in Java
Start Your Java Journey for Free Today
Conclusion
From the above article, we conclude that enums in Java provide a way to define a fixed set of constants with type safety, clear syntax, and object-like behavior. They have features like custom constructors, methods, and interface support, which are much more than simple constants. The Collections like EnumSet and EnumMap are specially optimized for enums; they are fast, memory-efficient, and keep natural enum order.
If you want to learn more about Java, you may refer to our Java Course to become an expert in it.
Enumeration in Java – FAQs
Q1. What is the use of an enum in Java?
Enums are used to define a fixed set of constant values that are type-safe and easy to manage in code.
Q2. Why use an enum instead of a class?
Because enums give you constant objects automatically, with less code and better safety.
Q3. Why use enum vs string?
Enums are better than strings because they avoid typos, support compiler checks, offer auto-complete, and are faster and more readable.
Q4. What are the disadvantages of an enum?
The key disadvantage of an enum is that it cannot extend classes and cannot have dynamic values at runtime.
Q5. Why is an enum best for a singleton?
An enum is best for a singleton because Java ensures an enum has only one instance by default.