Skip to content

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.

Beginner 16 min read·Lesson 26 of 39 in Java Programming

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

Java
enum Status { PENDING, PAID, SHIPPED }
enum Coin {
ONE(1), TWO(2), FIVE(5);
private final int value;
Coin(int value) { this.value = value; }
int value() { return value; }
}
record Point(int x, int y) {
Point { // compact constructor
if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
}
double distance() { return Math.sqrt(x * x + y * y); }
}
  • 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

Java
public class Main {
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
static String kind(Day d) {
return switch (d) {
case SAT, SUN -> "weekend";
default -> "weekday";
};
}
public static void main(String[] args) {
for (Day d : Day.values()) System.out.print(d + "(" + d.ordinal() + ") ");
System.out.println();
Day today = Day.valueOf("SAT");
System.out.println(today + " is a " + kind(today) + "; WED is a " + kind(Day.WED));
System.out.println(today == Day.SAT);
}
}
Output
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

Java
public class Main {
record Student(String name, int marks) {
Student {
if (marks < 0 || marks > 100) throw new IllegalArgumentException("marks out of range: " + marks);
name = name.trim();
}
boolean passed() { return marks >= 40; }
}
public static void main(String[] args) {
Student a = new Student(" Asha ", 82);
Student b = new Student("Asha", 82);
System.out.println(a + " passed=" + a.passed());
System.out.println(a.name() + " " + a.marks() + " equal=" + a.equals(b) + " sameHash=" + (a.hashCode() == b.hashCode()));
try {
new Student("Ravi", 120);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Output
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

Java
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public class Main {
enum Category {
FOOD(0.05), ELECTRONICS(0.18), BOOKS(0.0) {
@Override String label() { return "Books (tax free)"; }
};
private final double gst;
Category(double gst) { this.gst = gst; }
double gst() { return gst; }
String label() { return name().charAt(0) + name().substring(1).toLowerCase(); }
}
record Item(String name, Category category, long paise) {
long tax() { return Math.round(paise * category.gst()); }
}
public static void main(String[] args) {
List<Item> cart = List.of(
new Item("Rice 5kg", Category.FOOD, 42_000),
new Item("Headphones", Category.ELECTRONICS, 199_900),
new Item("Java book", Category.BOOKS, 65_000),
new Item("Biscuits", Category.FOOD, 3_000));
Map<Category, Long> totals = new EnumMap<>(Category.class);
for (Item i : cart) totals.merge(i.category(), i.paise() + i.tax(), Long::sum);
for (Map.Entry<Category, Long> e : totals.entrySet())
System.out.printf("%-18s Rs %,10.2f%n", e.getKey().label(), e.getValue() / 100.0);
long grand = totals.values().stream().mapToLong(Long::longValue).sum();
System.out.printf("%-18s Rs %,10.2f%n", "Total", grand / 100.0);
System.out.println(cart.get(1));
}
}
Output
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.
  • Item is 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.
  • EnumMap keeps keys in the enum's declaration order (FOOD, ELECTRONICS, BOOKS), and merge adds 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:

TextOutput
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]

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

void setSize(String size) // "Large", "lrg", "LARGE"...

Prefer

enum Size { SMALL, MEDIUM, LARGE }
void setSize(Size size)

Strings allow typos and invalid values; an enum restricts arguments to valid constants at compile time.

Calling get-style accessors on records

Avoid

student.getName()

Prefer

student.name()

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

  1. 1
    Write a TrafficLight enum with a next() method and a duration for each light.
  2. 2
    Model 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?
Practise this topic