Java Enum Iteration and Usage
In Java, an enum (enumeration) is a special data type used to define a fixed set of constants. Enums are ideal when you have a known group of values that should never change—such as days of the week, order status, or user roles.
One of the most common operations with enums is looping through all constants, which is easily done using the built-in values() method.
Looping Through Enum Values in Java
Every enum automatically provides a values() method that returns an array containing all defined constants in declaration order. This allows you to iterate through them using a for-each loop.
Example: Iterating Through an Enum
enum Priority {
LOW,
NORMAL,
HIGH,
URGENT
}
public class EnumIterationDemo {
public static void main(String[] args) {
System.out.println("Available priority levels:");
for (Priority p : Priority.values()) {
System.out.println("- " + p);
}
}
}
Output:
Available priority levels:
- LOW
- NORMAL
- HIGH
- URGENT
How it works:
- Priority.values() returns all enum constants.
- The enhanced for loop processes each constant.
- Enum constants print as their names by default.
Enums vs Classes in Java
Although enums resemble classes and can contain fields and methods, they have distinct characteristics and restrictions.
Similarities with Classes
An enum can:
- Declare fields (attributes)
- Define methods
- Have constructors
- Implement interfaces
Example: Enum with Fields and Methods
Enums can store additional data and behavior—similar to classes.
enum Membership {
BASIC(0),
SILVER(10),
GOLD(20),
PLATINUM(30);
private final int discount;
Membership(int discount) {
this.discount = discount;
}
public int getDiscount() {
return discount;
}
}
public class EnumWithDataDemo {
public static void main(String[] args) {
for (Membership m : Membership.values()) {
System.out.println(m + " members get " + m.getDiscount() + "% discount");
}
}
}
Output:
BASIC members get 0% discount
SILVER members get 10% discount
GOLD members get 20% discount
PLATINUM members get 30% discount
Why and When to Use Enums in Java
Use enums when you need a fixed, predefined set of related constants that represent a specific
category.
Common Use Cases
- Days of the week
- Months of the year
- Order or payment status
- User roles or permissions
- Traffic light states
- Card suits in a deck
- Application modes or levels
Benefits of Using Enums
- Type safety (prevents invalid values)
- Readable and self-documenting code
- Compile-time validation
- Built-in iteration (values())
- Can include behavior and data
Important Enum Rules in Java
- Enum constants are implicitly public static final
- Enums cannot extend other classes
- Enums can implement interfaces
- Constructors are always private or package-private
- Enum instances are created automatically by the JVM
Java Enum Constructor
In Java, an enum (enumeration) can define constructors, fields, and methods—just like a class. This allows each enum constant to carry additional data and behavior, making enums far more powerful than simple fixed values.
An enum constructor is executed automatically when each constant is created, and it cannot be invoked directly in your code.
How Enum Constructors Work in Java
When you declare enum constants with parameters, those values are passed to the enum constructor. The constructor initializes fields for each constant at class loading time.
Key rules:
- Enum constructors are always private (explicitly or implicitly)
- They run once per enum constant
- You cannot create enum objects using new
- Each constant becomes a singleton instance
Example: Enum with Constructor and Field
This example defines a Severity enum where each constant has a label describing its impact level.
enum Severity {
INFO("Informational message"),
WARNING("Potential issue detected"),
ERROR("Operation failed");
private final String message;
// Enum constructor (implicitly private)
Severity(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
public class EnumConstructorDemo {
public static void main(String[] args) {
Severity level = Severity.WARNING;
System.out.println("Selected: " + level);
System.out.println("Details: " + level.getMessage());
}
}
Output:
Selected: WARNING
Details: Potential issue detected
Explanation:
- Each enum constant passes a string to the constructor.
- The constructor assigns the value to message.
- Each constant stores its own immutable data.
Iterating Through Enum Constants with Constructor Values
You can loop through enum constants and access their associated data using values()
public class EnumLoopDemo {
public static void main(String[] args) {
for (Severity s : Severity.values()) {
System.out.println(s + " -> " + s.getMessage());
}
}
}
Output:
INFO -> Informational message
WARNING -> Potential issue detected
ERROR -> Operation failed
Why Use Constructors in Enums?
Enum constructors allow you to attach metadata to constants, which improves clarity and type safety compared to using separate maps or conditionals.
- Common Real-World Uses
- Status codes with descriptions
- User roles with permissions
- HTTP status enums
- Product categories with tax rates
- Application modes with configuration values
Important Notes About Enum Constructors
- Must be private or package-private (Java enforces this)
- Called automatically for each constant
- Fields are typically final
- Cannot be invoked manually
- Enum instances are created once by the JVM