Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Every enum idea in this module rests on one fact: each constant is a single object, created once and shared by the whole program. Most enum bugs come from forgetting that, or from hiding new constants behind a default.

Mistakes and fixes at a glance

The most common enum compile error comes from treating a constant like text. "UPI" is a String, and a PaymentMode variable accepts only PaymentMode constants.

Example 1 · A String where a constant belongs

StringModeDemo.javaJava
enum PaymentMode {    UPI, CARD, NET_BANKING}
public class StringModeDemo {    public static void main(String[] args) {        PaymentMode chosen = "UPI";        System.out.println("Paying by " + chosen);    }}
Sample compiler output
StringModeDemo.java:7: error: incompatible types: String cannot be converted to PaymentMode
        PaymentMode chosen = "UPI";
                             ^
1 error

What this code does

  • javac points at the text "UPI": a String can never be stored in a PaymentMode variable.
  • Fix: PaymentMode chosen = PaymentMode.UPI;. If the text really comes from a user, convert it with PaymentMode.valueOf(...).

Review: Why enums? (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:

Mistakes that compile

Some enum bugs give no error at all. Comparing constants with == is right, but the codes inside a fromCode() lookup are Strings, and == on Strings compares objects, not text.

Example 2 · Bug: == on String codes in a lookup

CodeCompareDemo.javaJava
enum TrainClass {    SLEEPER("SL"), AC_3_TIER("3A"), AC_2_TIER("2A");
    private final String code;
    TrainClass(String code) {        this.code = code;    }
    static TrainClass fromCode(String code) {        for (TrainClass t : values()) {            if (t.code == code) {                return t;            }        }        throw new IllegalArgumentException("Unknown class code: " + code);    }}
public class CodeCompareDemo {    public static void main(String[] args) {        String fromProgram = "3A";        String typedByUser = " 3A ".trim();        System.out.println(TrainClass.fromCode(fromProgram));        try {            System.out.println(TrainClass.fromCode(typedByUser));        } catch (IllegalArgumentException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
AC_3_TIER
Error: Unknown class code: 3A

What this code does

  • Comparing enum constants with == is right, but code is a String. The literal "3A" happens to be the same object as the one in the enum, so the first lookup works.
  • trim() builds a new String object, so == is false and the lookup fails for a perfectly good code. Fix: t.code.equals(code).

Example 3 · The fix: compare codes with equals()

CodeEqualsDemo.javaJava
enum TrainClass {    SLEEPER("SL"), AC_3_TIER("3A"), AC_2_TIER("2A");
    private final String code;
    TrainClass(String code) {        this.code = code;    }
    static TrainClass fromCode(String code) {        for (TrainClass t : values()) {            if (t.code.equals(code)) {                return t;            }        }        throw new IllegalArgumentException("Unknown class code: " + code);    }}
public class CodeEqualsDemo {    public static void main(String[] args) {        String fromProgram = "3A";        String typedByUser = " 3A ".trim();        System.out.println(TrainClass.fromCode(fromProgram));        try {            System.out.println(TrainClass.fromCode(typedByUser));        } catch (IllegalArgumentException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
AC_3_TIER
AC_3_TIER

What this code does

  • equals() compares the letters, so the trimmed "3A" now finds AC_3_TIER too, and the catch block is never reached.
  • Rule of thumb: == for enum constants, equals() for every String inside an enum.

Three more slips compile silently: saving ordinal() (a new constant shifts every number, see ordinal() (opens in a new tab)), a non-final enum field that one method changes for everyone (Keep enum fields private final (opens in a new tab)), and a default branch or default method body that quietly handles a new constant (A default branch hides new constants (opens in a new tab)).

Spot the bug

Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask three questions: is every value a real constant, is anything saved or compared by position or by == on text, and can a new constant slip through unnoticed?

Find the bug

Find the enum bug

Select the line that is wrong.

The plan is saved to a file and must still load after new plans are added.

Round 1 of 5

When in doubt, trace the constants

A program prints constructor messages in an order you did not expect. Trace it: the first use of the enum builds every constant, in declaration order, and after that valueOf() and values() only hand back the same objects.

Trace the code

Trace when the constants are made

enum Level {
LOW(1), HIGH(9);
private final int score;
Level(int score) {
this.score = score;
System.out.println("made " + name());
}
int getScore() {
return score;
}
}
public class LevelTrace {
public static void main(String[] args) {
System.out.println("start");
Level a = Level.HIGH;
Level b = Level.valueOf("HIGH");
System.out.println(a == b);
System.out.println(a.getScore() + Level.values().length);
}
}

Variables

None yet.

Output

start

Line 18main starts. Level has not been used yet, so no constant exists.

Step 1 of 9

Finish up

Mark complete & continue

Next: Must-do problems: Enums