Java / Java 21 Interview Questions
What capabilities do Java enums have beyond simple named constants?
Java enums are full-fledged classes that happen to have a fixed number of instances. This makes them far more powerful than C-style enums and eliminates entire categories of bugs that arise from using int constants.
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; // kg
private final double radius; // meters
Planet(double mass, double radius) { // constructor
this.mass = mass;
this.radius = radius;
}
static final double G = 6.67300E-11;
double surfaceGravity() { return G * mass / (radius * radius); }
double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); }
}
double earthWeight = 75.0;
double mass = earthWeight / Planet.EARTH.surfaceGravity();
for (Planet p : Planet.values()) {
System.out.printf("Weight on %s = %6.2f%n", p, p.surfaceWeight(mass));
}
// Abstract methods — each constant provides its own implementation
enum Operation {
PLUS("+ ") { @Override double apply(double x, double y) { return x + y; } },
MINUS("-") { @Override double apply(double x, double y) { return x - y; } };
private final String symbol;
Operation(String symbol) { this.symbol = symbol; }
abstract double apply(double x, double y);
@Override public String toString() { return symbol; }
}
// Enum with switch (Java 21 — pattern matching works on enums)
int priority = switch (severity) {
case CRITICAL -> 1;
case HIGH -> 2;
case MEDIUM -> 3;
case LOW -> 4;
};
// EnumSet and EnumMap — fast, memory-efficient specialisations
EnumSet workdays = EnumSet.range(MONDAY, FRIDAY);
EnumMap weights = new EnumMap<>(Planet.class);
More Related questions...