Enum Basics in Java
What is an Enum?
In Java, an enum (enumeration) is a special type of class used to define a collection of constants. Enums provide a way to create a group of related constants with more functionality than traditional static final variables.
Defining an Enum
Here's a basic example of an enum in Java:
public enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Enum Characteristics
Enums in Java have several important characteristics:
Feature |
Description |
Type Safety |
Enums provide compile-time type safety |
Singleton |
Each enum constant is a singleton instance |
Methods |
Enums can have methods, constructors, and fields |
Creating Enums with Additional Properties
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // in kilograms
private final double radius; // in meters
// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// Method to calculate surface gravity
public double surfaceGravity() {
final double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
Enum Methods and Behaviors
Enums come with built-in methods:
DaysOfWeek day = DaysOfWeek.MONDAY;
System.out.println(day.name()); // Prints "MONDAY"
System.out.println(day.ordinal()); // Prints 0 (index in enum)
System.out.println(day.toString()); // Prints "MONDAY"
Enum in Switch Statements
Enums work perfectly with switch statements:
DaysOfWeek day = DaysOfWeek.WEDNESDAY;
switch (day) {
case MONDAY:
System.out.println("Start of the work week");
break;
case WEDNESDAY:
System.out.println("Middle of the work week");
break;
case FRIDAY:
System.out.println("End of the work week");
break;
default:
System.out.println("Weekend");
}
Enum Iteration
You can easily iterate through enum constants:
for (DaysOfWeek day : DaysOfWeek.values()) {
System.out.println(day);
}
Why Use Enums?
- Provide type safety
- Improve code readability
- Represent a fixed set of constants
- Allow for more complex constant definitions
At LabEx, we recommend using enums to create more robust and meaningful code structures in Java applications.