Module 7 · Core Java APIs — topic 4 of 4
Enums and Records
Type-safe constants with enum, enums with fields, constructors and methods, EnumMap, and concise immutable data classes with record (Java 16), including compact constructors.
Learning objectives
- Define enums with fields and methods and use them in switch
- Use values(), valueOf(), ordinal() and EnumMap
- Write records with validation in a compact constructor
Definition
An enum is a class with a fixed set of named instances, such as the days of the week. A record (Java 16) is a concise, immutable data class whose fields, constructor, accessors, equals, hashCode and toString are generated from its components.
Introduction
Using plain ints or strings for fixed choices — status = 2, size = "lrg" — invites typos and invalid values. Enums make the set of choices part of the type system. Records solve a different everyday problem: writing small data classes without pages of boilerplate.
Why it matters
Enums are used for states, categories, options and commands in almost every application.
Records are now the standard way to write data carriers — DTOs, map keys, results — in modern Java.
Detailed explanation
Basic enums. enum Size { SMALL, MEDIUM, LARGE } declares a type with exactly three instances. Compare them with == (there is only one instance of each), and switch on them directly.
Built-in methods. Size.values() returns all constants in declaration order, Size.valueOf("LARGE") converts a name (throwing IllegalArgumentException for unknown names), ordinal() gives the position and name() the identifier.
Enums are classes. They can have fields, a private constructor and methods, and each constant can even override a method. enum Planet { EARTH(5.97e24, 6.37e6), ... }.
EnumMap and EnumSet are very fast map and set implementations for enum keys.
Records (Java 16). record Point(int x, int y) { } creates a final class with private final fields x and y, a canonical constructor, accessor methods x() and y() (no get prefix), and value-based equals, hashCode and toString.
Compact constructors validate or normalise input without repeating the assignments: record Range(int lo, int hi) { Range { if (lo > hi) throw new IllegalArgumentException(); } }.
Records can have static fields, static and instance methods, and implement interfaces, but cannot extend another class or declare extra instance fields. If a component is a mutable object (like a List), copy it in the compact constructor to keep the record truly immutable.
Syntax
- Enum constructors are always private.
- Record accessors are named after components: p.x(), not p.getX().
- Records are final and their fields are final.
Code examples
An enum in a switch
MON(0) TUE(1) WED(2) THU(3) FRI(4) SAT(5) SUN(6) SAT is a weekend; WED is a weekday true
A record
Student[name=Asha, marks=82] passed=true Asha 82 equal=true sameHash=true marks out of range: 120
More examples
Enums with behaviour, EnumMap and records together
Food Rs 472.50 Electronics Rs 2,358.82 Books (tax free) Rs 650.00 Total Rs 3,481.32 Item[name=Headphones, category=ELECTRONICS, paise=199900]
Step-by-step explanation
- Each Category constant passes its GST rate to the private constructor; BOOKS also overrides
label()with a constant-specific body. Itemis a record: its constructor, accessors (category(),paise()), equals, hashCode and toString are generated.tax()is an ordinary instance method on the record, using the enum's rate.EnumMapkeeps keys in the enum's declaration order (FOOD, ELECTRONICS, BOOKS), andmergeadds each item's price plus tax to its category total.- Food: 420 + 21 + 30 + 1.50 = 472.50; Electronics: 1,999 + 359.82 = 2,358.82; the record's generated toString prints all components.
Expected output
Running “Enums with behaviour, EnumMap and records together” prints exactly:
Practical applications
- Order states (PENDING, PAID, SHIPPED) and user roles
- Configuration options and command types in CLIs
- Records as DTOs returned from REST APIs and as composite map keys
- Records for method results that carry several values
Best practices
- Use enums instead of int or String constants for fixed sets.
- Don't rely on ordinal() for stored data; it changes if constants are reordered.
- Use records for immutable data carriers and validate in the compact constructor.
Common mistakes
Using strings for fixed choices
Avoid
Prefer
Strings allow typos and invalid values; an enum restricts arguments to valid constants at compile time.
Calling get-style accessors on records
Avoid
Prefer
Record accessors are named exactly after the components, without a get prefix.
Important notes
- Records became standard in Java 16; enums have existed since Java 5.
- A record's components should be immutable or defensively copied (for example with List.copyOf) to keep the record immutable.
Key takeaways
- Enums define a fixed set of instances and can have fields, constructors and methods.
- values(), valueOf() and EnumMap make enums easy to iterate and look up.
- Records generate constructor, accessors, equals, hashCode and toString for immutable data.
Try it yourself
- 1Write a TrafficLight enum with a
next()method and a duration for each light. - 2Model a
Money(long paise, String currency)record that rejects negative amounts and adds two Money values of the same currency.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
8 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- BeginnerWhich is true about records?