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);
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
