Enum in Java: A Complete Guide with Examples - Quiz
Total: 7 questions
1. How do you compare enum constants in Java: equals() or ==?
How do you compare enum constants in Java: equals() or ==?
You can use both the equals() method and the == operator, and the result is the same, because each enum constant exists as a single instance. equals() in java.lang.Enum is final and returns true only for the very same constant.
For enums, == is actually better: it cannot throw NullPointerException when the left side is null, and the compiler rejects a == comparison between constants of two different enums right away. To compare constants by declaration order, use compareTo().
2. What do the values() and valueOf() methods of a Java enum do, and which exceptions can valueOf() throw?
What do the values() and valueOf() methods of a Java enum do, and which exceptions can valueOf() throw?
Both methods are static, and the compiler generates them in every enum (they are not declared in java.lang.Enum).
values() returns an array of all constants in declaration order. It is the standard way to loop over an enum. Each call returns a new copy of the array.
valueOf(String) returns the constant whose name matches the string exactly (case-sensitive, whitespace is not trimmed). If no constant has that name, it throws IllegalArgumentException. If you pass null, it throws NullPointerException.
CoffeeSize s = CoffeeSize.valueOf("BIG"); // BIG
CoffeeSize.valueOf("big"); // IllegalArgumentException
3. What is the difference between name() and toString() in a Java enum, and what does ordinal() return?
What is the difference between name() and toString() in a Java enum, and what does ordinal() return?
name() is final and always returns the constant name exactly as written in the source code. toString() returns the same thing by default, but you can override it, for example to show a user-friendly label. To convert an enum to a string and back with valueOf(), use name(): valueOf() looks up a constant by its name, not by the result of toString().
ordinal() returns the zero-based position of the constant in the enum declaration. Do not store ordinal() in a database or file: if a constant is inserted in the middle or the list is reordered, the numbers shift. Store name() or a dedicated code field instead.
4. What access modifier can an enum constructor have, and how is it called?
What access modifier can an enum constructor have, and how is it called?
An enum constructor is always private. If you omit the modifier, private is implied, and declaring it public or protected is a compile error. You cannot create an enum instance with new.
The constructor runs when the enum is initialized: you put the arguments in parentheses after a constant name. The list of constants must come first and must end with a semicolon if other members follow it. Constructors can be overloaded: a constant without parentheses uses the no-argument constructor.
enum CoffeeSize {
BIG(100), HUGE(150), OVERWHELMING(200);
private final int ml;
CoffeeSize(int ml) { this.ml = ml; }
public int getMl() { return ml; }
}
5. How do you use an enum in a switch statement, and what happens if the enum variable is null?
How do you use an enum in a switch statement, and what happens if the enum variable is null?
Every case label must be a constant of the same enum as the switch expression. You usually write the simple constant name (case BIG). The qualified name case CoffeeSize.BIG is allowed only since Java 21.
In an arrow-style switch expression (Java 14+), you do not need a default branch if every constant has a case: the compiler checks exhaustiveness, so adding a new constant breaks compilation until the switch is updated.
String message = switch (size) {
case BIG -> "Big cup";
case HUGE -> "Huge cup";
case OVERWHELMING -> "Overwhelming cup";
};
If the enum variable is null, a classic switch throws NullPointerException, and a default branch does not prevent it.
6. Can a Java enum extend a class, implement interfaces, or declare abstract methods?
Can a Java enum extend a class, implement interfaces, or declare abstract methods?
An enum cannot explicitly extend a class: every enum implicitly extends java.lang.Enum, and Java has no multiple class inheritance, so an extends clause on an enum does not compile. You cannot extend an enum either, because it is implicitly final.
An enum can implement any number of interfaces. You can implement an interface method once for the whole enum or separately in the body of each constant.
An enum can declare an abstract method, and then every constant must implement it in its own body. A constant with a body is an instance of an anonymous subclass, so getClass() returns a class like Operation$1; use getDeclaringClass() to get the enum type itself.
enum Operation {
PLUS { public int apply(int a, int b) { return a + b; } },
MINUS { public int apply(int a, int b) { return a - b; } };
public abstract int apply(int a, int b);
}
7. What are EnumSet and EnumMap, and why are they better than HashSet and HashMap for enums?
What are EnumSet and EnumMap, and why are they better than HashSet and HashMap for enums?
They are collections in the java.util package built specifically for enums:
EnumSetis a set of constants from one enum, stored internally as a bit vector.EnumMapis a map with enum constants as keys, backed by an array indexed byordinal().
Because they rely on constant ordinals, they are faster and more compact than HashSet and HashMap, and they iterate in the declaration order of the constants.
Set<CoffeeSize> large = EnumSet.of(CoffeeSize.HUGE, CoffeeSize.OVERWHELMING);
Map<CoffeeSize, Integer> prices = new EnumMap<>(CoffeeSize.class);