Enums in Java are a special type of class that represent a group of constants (unchangeable variables). They were introduced in Java 5 and provide a type-safe way to define a fixed set of constants.
Basic Enum Syntax
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Key Features of Enums
Type Safety: You can't assign any value other than those predefined enum values.
Can Have Fields, Methods, and Constructors:
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() {
return 6.67300E-11 * mass / (radius * radius);
}
}
- Can Implement Interfaces:
public interface Printable {
void print();
}
public enum Color implements Printable {
RED {
public void print() {
System.out.println("Red color");
}
},
GREEN {
public void print() {
System.out.println("Green color");
}
};
}
- Can Be Used in Switch Statements:
Day day = Day.MONDAY;
switch(day) {
case MONDAY:
System.out.println("Start of work week");
break;
case FRIDAY:
System.out.println("End of work week");
break;
}
Common Methods
-
values()
: Returns an array of all enum constants -
valueOf(String name)
: Returns the enum constant with the specified name -
ordinal()
: Returns the position of the enum constant in the declaration (starting from 0) -
name()
: Returns the name of the enum constant as a string
Example Usage
java
public class EnumExample {
public static void main(String[] args) {
// Accessing enum constants
Day today = Day.WEDNESDAY;
System.out.println("Today is " + today);
// Using values() method
for (Day day : Day.values()) {
System.out.println(day);
}
// Using valueOf()
Day day = Day.valueOf("FRIDAY");
System.out.println("Day is " + day);
}
}
Enums are particularly useful when you have a variable that should only take one of a small set of possible values, making your code more readable and less error-prone.
Top comments (0)