Enums, short for "enumerated types," are a powerful feature in Java programming. They provide a way to define a fixed set of constants, making code more readable and type-safe.
An enum is a special type of class in Java that represents a group of constants. These constants are typically uppercase and separated by commas. Enums are particularly useful when you have a fixed set of values that a variable can take.
Here's the basic syntax for declaring an enum in Java:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3
}
Let's look at a practical example of creating and using an enum:
public enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumExample {
public static void main(String[] args) {
DaysOfWeek today = DaysOfWeek.WEDNESDAY;
System.out.println("Today is " + today);
}
}
Java enums come with built-in methods that can be very useful:
values()
: Returns an array of all enum constantsvalueOf(String name)
: Returns the enum constant with the specified nameordinal()
: Returns the position of the enum constant (zero-based)Enums can have properties, constructors, and methods, making them even more powerful:
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
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double surfaceGravity() {
double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
Enums work exceptionally well with Java switch statements, providing a clean and type-safe way to handle multiple cases:
DaysOfWeek day = DaysOfWeek.FRIDAY;
switch (day) {
case MONDAY:
System.out.println("Start of the work week");
break;
case FRIDAY:
System.out.println("TGIF!");
break;
default:
System.out.println("Mid-week");
}
Java enums are a versatile feature that can significantly improve code readability and maintainability. They provide type-safety, can have properties and methods, and work seamlessly with other Java constructs like switch statements. By mastering enums, you'll have another powerful tool in your Java programming toolkit.
For more advanced Java topics, consider exploring Java Generics or Java Collections.