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
enum PaymentMode { UPI, CARD, NET_BANKING}
public class StringModeDemo { public static void main(String[] args) { PaymentMode chosen = "UPI"; System.out.println("Paying by " + chosen); }}StringModeDemo.java:7: error: incompatible types: String cannot be converted to PaymentMode
PaymentMode chosen = "UPI";
^
1 errorWhat this code does
- javac points at the text
"UPI": a String can never be stored in aPaymentModevariable. - Fix:
PaymentMode chosen = PaymentMode.UPI;. If the text really comes from a user, convert it withPaymentMode.valueOf(...).
Review: Why enums? (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
enum classes may not be instantiated→newon an enum → use a constant. Review: Why enums? (opens in a new tab)IllegalArgumentException: No enum constant ...→valueOfgot text that is not an exact name →trim(),toUpperCase()and catch it. Review: Built-in enum methods (opens in a new tab)the switch expression does not cover all possible input valuesoran enum switch case label must be the unqualified name...→ add the missing case; writecase UPI. Review: switch on an enum (opens in a new tab)',', '}', or ';' expected,enum constant expected hereormodifier public not allowed here→ constants first, then;, private constructor. Review: Enums with fields (opens in a new tab)Operation is abstract; cannot be instantiatedat a constant, or'{' expectedafterenum X extends Y→ give the constant its body; useimplements. Review: Enums with behaviour (opens in a new tab)
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
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()); } }}AC_3_TIER Error: Unknown class code: 3A
What this code does
- Comparing enum constants with
==is right, butcodeis 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==isfalseand the lookup fails for a perfectly good code. Fix:t.code.equals(code).
Example 3 · The fix: compare codes with equals()
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()); } }}AC_3_TIER AC_3_TIER
What this code does
equals()compares the letters, so the trimmed"3A"now findsAC_3_TIERtoo, and thecatchblock 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 5When 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
Variables
None yet.
Output
start
Line 18main starts. Level has not been used yet, so no constant exists.
Finish up
Mark complete & continue
Next: Must-do problems: Enums