Enum Basics in Java
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 type safety and clarity compared to traditional integer or string constants.
Defining an Enum
Here's a basic example of an enum definition:
public enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Enum Characteristics
Enums in Java have several key characteristics:
Feature |
Description |
Type Safety |
Enums provide compile-time type checking |
Singleton |
Each enum constant is a singleton instance |
Methods |
Enums can have methods, constructors, and fields |
Advanced Enum Example
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 Usage
Enums come with built-in methods:
DaysOfWeek today = DaysOfWeek.MONDAY;
// Get the name of the enum constant
String name = today.name();
// Get the ordinal (position) of the enum constant
int position = today.ordinal();
// Convert string to enum
DaysOfWeek day = DaysOfWeek.valueOf("TUESDAY");
When to Use Enums
Enums are ideal for:
- Representing a fixed set of constants
- Creating type-safe enumeration of values
- Defining a group of related constants
- Implementing state machines
Enum Workflow
graph TD
A[Define Enum] --> B[Create Enum Constants]
B --> C[Use Enum in Code]
C --> D[Access Enum Methods]
D --> E[Perform Operations]
By understanding these basics, developers can leverage enums to write more robust and readable Java code. LabEx recommends practicing enum implementation to gain proficiency.