Of course! In Java, an enum (short for enumeration) is a special data type that allows a variable to be a set of predefined constants. The values of an enum type are its constants.
Here’s a comprehensive guide covering how to define, use, and work with enum values in Java.
Basic Definition and Usage
An enum is defined using the enum keyword. Each constant in the enum is separated by a comma.
Example: Defining a simple Day enum
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
How to use an enum value:
You declare a variable of the enum type and assign it one of its constant values.
public class Main {
public static void main(String[] args) {
// Declare a variable of type Day
Day today;
// Assign a value to the variable
today = Day.WEDNESDAY;
// Use the enum value in a switch statement
switch (today) {
case MONDAY:
System.out.println("The weekend is over.");
break;
case FRIDAY:
System.out.println("TGIF! Let's plan for the weekend.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend! Time to relax.");
break;
default:
System.out.println("It's a weekday. Keep working hard.");
}
// You can also compare enum values using '==' (recommended)
if (today == Day.WEDNESDAY) {
System.out.println("Yes, it's Wednesday.");
}
// Using .name() to get the constant name as a String
String dayName = today.name(); // Returns "WEDNESDAY"
System.out.println("Day name: " + dayName);
}
}
Enum with Fields, Constructors, and Methods
Enums are much more powerful than simple constants. You can add fields, constructors, and methods to make them behave like full-fledged classes.
Example: An enum for different planets with properties
public enum Planet {
// Each constant is an instance of the Planet enum
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
// Fields (instance variables)
private final double mass; // in kilograms
private final double radius; // in meters
// Constructor (must be private or package-private)
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// Public methods
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
// A more complex method
public double surfaceGravity() {
// G (gravitational constant) is 6.67300E-11
return G * mass / (radius * radius);
}
private static final double G = 6.67300E-11; // Gravitational constant
}
How to use this enhanced enum:
public class Main {
public static void main(String[] args) {
Planet earth = Planet.EARTH;
System.out.println("Earth's mass: " + earth.getMass());
System.out.println("Earth's radius: " + earth.getRadius());
System.out.printf("Earth's surface gravity: %.2f m/s^2\n", earth.surfaceGravity());
// You can also iterate over all values in an enum
System.out.println("\nAll Planets:");
for (Planet planet : Planet.values()) {
System.out.println(planet + " - Gravity: " + planet.surfaceGravity());
}
}
}
Key Methods for Enum Values
The java.lang.Enum class provides several useful methods that are available for all your enums.
| Method | Description | Example |
|---|---|---|
values() |
Returns an array containing all the values of the enum, in the order they are declared. | Day[] allDays = Day.values(); |
valueOf(String name) |
Returns the enum constant of the specified enum type with the specified name. Throws IllegalArgumentException if not found. |
Day monday = Day.valueOf("MONDAY"); |
name() |
Returns the name of this enum constant, as declared in its enum declaration. It's the same as toString() by default. |
String name = Day.MONDAY.name(); // "MONDAY" |
toString() |
Returns the name of this enum constant, as contained in the declaration. You can override this to provide a custom string representation. | System.out.println(Day.MONDAY); // Prints "MONDAY" |
ordinal() |
Returns the order of this enum constant's declaration, where the initial constant is assigned an ordinal of zero. | int index = Day.MONDAY.ordinal(); // 0 |
Example demonstrating these methods:
public class Main {
public static void main(String[] args) {
// 1. values()
System.out.println("--- Using values() ---");
for (Day day : Day.values()) {
System.out.println(day);
}
// 2. valueOf()
System.out.println("\n--- Using valueOf() ---");
try {
Day friday = Day.valueOf("FRIDAY");
System.out.println("Found: " + friday);
} catch (IllegalArgumentException e) {
System.out.println("Enum constant not found.");
}
// 3. name() and toString()
System.out.println("\n--- Using name() and toString() ---");
Day today = Day.SATURDAY;
System.out.println("name(): " + today.name());
System.out.println("toString(): " + today.toString());
// 4. ordinal()
System.out.println("\n--- Using ordinal() ---");
System.out.println("The ordinal of SATURDAY is: " + today.ordinal()); // Will be 5
}
}
Advanced: Implementing an Interface
Enums can implement interfaces, allowing you to define a common behavior for all constants.
Example: An interface for a Described object
interface Described {
String getDescription();
}
Example: An enum that implements the interface
public enum HttpStatus implements Described {
OK(200, "Request successful"),
NOT_FOUND(404, "Resource not found"),
INTERNAL_SERVER_ERROR(500, "Server encountered an error");
private final int code;
private final String description;
HttpStatus(int code, String description) {
this.code = code;
this.description = description;
}
@Override
public String getDescription() {
return this.description;
}
public int getCode() {
return this.code;
}
}
Usage:
public class Main {
public static void main(String[] args) {
HttpStatus status = HttpStatus.NOT_FOUND;
// Since all HttpStatus values implement Described,
// we can treat them as such.
printStatusDescription(status);
}
public static void printStatusDescription(Described described) {
System.out.println("Description: " + described.getDescription());
}
}
Advanced: Using an Enum in a switch Statement
Enums are particularly well-suited for switch statements because they are type-safe, preventing you from accidentally using an invalid value.
public class Main {
public static void printDayType(Day day) {
switch (day) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
System.out.println(day + " is a Weekday.");
break;
case SATURDAY:
case SUNDAY:
System.out.println(day + " is a Weekend day.");
break;
// No default case needed because the compiler ensures
// all possible enum values are handled.
}
}
public static void main(String[] args) {
printDayType(Day.MONDAY); // Output: MONDAY is a Weekday.
printDayType(Day.SATURDAY); // Output: SATURDAY is a Weekend day.
}
}
Summary
| Feature | Description | Example |
|---|---|---|
| Constants | Enum values are constants, typically in UPPER_CASE. |
Day.MONDAY |
| Type-Safe | You can't assign an invalid value to an enum variable. | Day myDay = Day.FOO; // Compile Error! |
| Fields & Methods | Enums can have fields, constructors, and methods like classes. | Planet.EARTH.getMass() |
| Iteration | Use values() to get an array of all constants. |
for (Day d : Day.values()) { ... } |
| Switch | Perfect for switch statements for clean, readable code. |
switch (day) { case MONDAY: ... } |
| Interfaces | Enums can implement interfaces to enforce a common contract. | enum Color implements Paintable { ... } |
