Two modern Java features remove a lot of boilerplate. An enum defines a type with a fixed set of named values, such as the days of the week or the levels of a warning. A record (Java 16+) defines a small immutable data class in one line, with the constructor, accessors, equals, hashCode and toString written for you. This lesson covers both.
In this lesson you will learn
- Declaring an enum and looping over its values
- Enum fields, constructors and methods
- Using enums with switch expressions
- Declaring a record and what Java generates
- Validating data in a compact constructor
Enums
enum Level {
LOW(1), MEDIUM(5), HIGH(10); // constants with a value
private final int weight;
Level(int weight) { this.weight = weight; }
int weight() { return weight; }
}
public class Main {
public static void main(String[] args) {
Level l = Level.MEDIUM;
System.out.println(l + " weight=" + l.weight() + " ordinal=" + l.ordinal());
for (Level x : Level.values()) System.out.print(x + " ");
System.out.println();
Level parsed = Level.valueOf("HIGH");
String advice = switch (parsed) {
case LOW -> "ignore";
case MEDIUM -> "watch";
case HIGH -> "act now";
};
System.out.println(parsed + ": " + advice);
System.out.println(l == Level.MEDIUM); // enums compare safely with ==
}
}
Output
MEDIUM weight=5 ordinal=1
LOW MEDIUM HIGH
HIGH: act now
true
enum Level { LOW, MEDIUM, HIGH }creates a type with exactly three possible values. A variable of typeLevelcannot hold anything else, which is much safer than using strings or int codes.- Enums can have fields, a constructor (always private) and methods. Here each constant carries a
weight. values()returns all constants in declaration order,ordinal()gives the position, andvalueOf("HIGH")converts a string.valueOfthrowsIllegalArgumentExceptionfor an unknown name.- A
switchexpression over an enum can list every constant without adefault; the compiler checks that all cases are covered. See if-else and switch. - Each constant exists exactly once, so comparing with
==is safe.
Records
import java.util.HashSet;
import java.util.Set;
record Point(int x, int y) {
Point { // compact constructor: validation
if (x < 0 || y < 0) throw new IllegalArgumentException("negative coordinate");
}
double distanceFromOrigin() { return Math.sqrt(x * x + y * y); }
}
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p); // generated toString
System.out.println("x=" + p.x() + " y=" + p.y()); // generated accessors
System.out.println("distance=" + p.distanceFromOrigin());
Point q = new Point(3, 4);
System.out.println("equals: " + p.equals(q) + ", same object: " + (p == q));
Set<Point> set = new HashSet<>();
set.add(p); set.add(q);
System.out.println("set size: " + set.size()); // generated hashCode
try {
new Point(-1, 2);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Output
Point[x=3, y=4]
x=3 y=4
distance=5.0
equals: true, same object: false
set size: 1
Rejected: negative coordinate
record Point(int x, int y) {}declares two private final fields and generates a constructor, accessor methodsx()andy()(no “get” prefix),toString,equalsandhashCode.- Two records with the same values are
equals, so aHashSetstores only one of them. They are still separate objects, so==is false. - The compact constructor
Point { ... }runs before the fields are set and is the place to validate arguments. - Records can have extra methods and static members, and can implement interfaces, but they cannot extend another class and their fields cannot change.
Record vs Ordinary Class
| Record | Regular class | |
|---|---|---|
| Fields | Final, set once | Any |
| equals / hashCode / toString | Generated from all fields | Written by hand (or inherited from Object) |
| Inheritance | Cannot extend a class | Can extend one class |
| Best for | Data carriers: DTOs, map keys, return values | Objects with behaviour and changing state |
Compare the record above with the hand-written Student class in Classes and Objects to see how much code a record saves.
Common Mistakes
- Calling
p.getX()on a record; the accessor isp.x(). - Trying to change a record field; create a new record instead.
- Relying on
ordinal()to store enums in a database; adding a constant later shifts the numbers. Storename()instead. - Passing user input straight to
valueOfwithout handling the exception for unknown names.
Practice Exercises
Exercise 1. Write an enum Day with a method isWeekend() that returns true for Friday and Saturday (the weekend in Bangladesh).
Show answer
enum Day {
SUN, MON, TUE, WED, THU, FRI, SAT;
boolean isWeekend() { return this == FRI || this == SAT; }
}
Exercise 2. Write a record Product(String name, double price) that rejects a negative price.
Show answer
record Product(String name, double price) {
Product {
if (price < 0) throw new IllegalArgumentException("price must be positive");
}
}
Frequently Asked Questions
Are records truly immutable?
Their fields cannot be reassigned. But if a field holds a mutable object, such as a List, that object can still be changed. Copy it with List.copyOf in the constructor for full immutability.
Can an enum implement an interface?
Yes. Enums cannot extend a class (they already extend java.lang.Enum), but they can implement any number of interfaces.
Summary
- Enums model a fixed set of named constants and can carry fields and methods.
- Use
values(),valueOf()and switch expressions with enums. - Records are concise immutable data classes with generated methods.
- Validate record data in a compact constructor.
Next: Java Lambda Expressions.
