Reading history

Java Enums and Records with Examples

5 min read 0 views

Learn Java enums with fields, methods and switch expressions, and Java records: generated accessors, equals, hashCode, toString and compact constructors.

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 type Level cannot 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, and valueOf("HIGH") converts a string. valueOf throws IllegalArgumentException for an unknown name.
  • A switch expression over an enum can list every constant without a default; 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 methods x() and y() (no “get” prefix), toString, equals and hashCode.
  • Two records with the same values are equals, so a HashSet stores 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

RecordRegular class
FieldsFinal, set onceAny
equals / hashCode / toStringGenerated from all fieldsWritten by hand (or inherited from Object)
InheritanceCannot extend a classCan extend one class
Best forData carriers: DTOs, map keys, return valuesObjects 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

  1. Calling p.getX() on a record; the accessor is p.x().
  2. Trying to change a record field; create a new record instead.
  3. Relying on ordinal() to store enums in a database; adding a constant later shifts the numbers. Store name() instead.
  4. Passing user input straight to valueOf without 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.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *