Enum Basics in Java
What is an Enum?
An enumeration (enum) in Java is a special type of class used to define a collection of constants. Unlike traditional classes, enums provide a way to create a fixed set of predefined values that represent a specific type of data.
Basic Enum Declaration
Here's a simple example of an enum declaration in Java:
public enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Key Characteristics of Enums
Characteristic |
Description |
Type-Safety |
Enums provide compile-time type safety |
Singleton |
Each enum constant is a singleton instance |
Iterable |
Can be easily iterated using values() method |
Enum Methods and Features
graph TD
A[Enum Declaration] --> B[Default Methods]
A --> C[Custom Methods]
A --> D[Constructor Support]
B --> E[values()]
B --> F[valueOf()]
C --> G[Custom Business Logic]
Basic Enum Usage Example
public class EnumDemo {
public static void main(String[] args) {
DaysOfWeek today = DaysOfWeek.MONDAY;
// Iterate through enum values
for (DaysOfWeek day : DaysOfWeek.values()) {
System.out.println(day);
}
// Compare enum values
if (today == DaysOfWeek.MONDAY) {
System.out.println("It's the start of the week!");
}
}
}
Why Use Enums?
- Improved code readability
- Type-safe constants
- Easy to use in switch statements
- Prevents invalid values
Enum vs Static Final Constants
While static final constants can achieve similar results, enums offer more robust and type-safe solutions:
// Enum approach
public enum Status {
ACTIVE, INACTIVE, PENDING
}
// Static final approach (less robust)
public class StatusConstants {
public static final int STATUS_ACTIVE = 1;
public static final int STATUS_INACTIVE = 0;
public static final int STATUS_PENDING = 2;
}
Enums in Java are implemented as classes and have minimal performance overhead. They are compiled to efficient bytecode and provide type safety at compile-time.
Note: LabEx recommends using enums for creating well-structured, type-safe constant collections in Java applications.