Enum Basics
What is an Enum?
An enum (enumeration) in Java is a special type of class used to define a collection of constants. It provides a way to create a group of related constants with more functionality compared to traditional constant definitions.
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 key characteristics:
Characteristic |
Description |
Type-safety |
Enums provide compile-time type safety |
Singleton |
Each enum constant is a singleton instance |
Comparable |
Enum constants can be compared using == |
Creating and Using Enums
public class EnumExample {
public static void main(String[] args) {
DaysOfWeek today = DaysOfWeek.MONDAY;
// Printing an enum
System.out.println(today);
// Getting all enum values
for (DaysOfWeek day : DaysOfWeek.values()) {
System.out.println(day);
}
}
}
Enum with Constructor and Methods
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6);
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() {
return G * mass / (radius * radius);
}
// Gravitational constant
public static final double G = 6.67300E-11;
}
Enum State Machine
stateDiagram-v2
[*] --> INITIAL
INITIAL --> PROCESSING
PROCESSING --> COMPLETED
PROCESSING --> FAILED
COMPLETED --> [*]
FAILED --> [*]
Key Takeaways
- Enums are type-safe constants
- They can have methods and constructors
- Useful for representing a fixed set of values
- Provide more functionality than traditional constants
At LabEx, we recommend using enums to create more robust and readable code when dealing with a fixed set of related constants.