Java Enums & Records

Enums

An enum is a fixed set of named constants — far safer than passing strings around.

Java
public enum Status {
    NEW, PAID, SHIPPED, CANCELLED
}

Status s = Status.PAID;

if (s == Status.PAID) {          // == is fine and correct for enums
    System.out.println("Payment received");
}

Because the set is closed, the compiler can check a switch is exhaustive:

Java
String label = switch (s) {
    case NEW       -> "Awaiting payment";
    case PAID      -> "Payment received";
    case SHIPPED   -> "On the way";
    case CANCELLED -> "Cancelled";
};

Add a new constant later and every such switch fails to compile until you handle it — exactly the reminder you want.

Enums with fields and methods

Java
public enum Currency {
    NPR("Nepalese Rupee", "Rs."),
    USD("US Dollar", "$"),
    INR("Indian Rupee", "₹");

    private final String label;
    private final String symbol;

    Currency(String label, String symbol) {
        this.label = label;
        this.symbol = symbol;
    }

    public String getLabel()  { return label; }
    public String getSymbol() { return symbol; }
}

System.out.println(Currency.NPR.getSymbol());  // Rs.

Useful built-ins

Java
Status.valueOf("PAID");     // string → enum (throws if invalid)
Status.PAID.name();         // "PAID"
Status.PAID.ordinal();      // 1 — position, avoid relying on this
Status.values();            // array of all constants

Records (Java 16+)

A record is an immutable data carrier. This one line replaces a constructor, getters, equals(), hashCode(), and toString():

Java
public record Point(int x, int y) {}

Point p = new Point(3, 4);
System.out.println(p.x());      // 3 — accessor, no "get" prefix
System.out.println(p);           // Point[x=3, y=4]
System.out.println(p.equals(new Point(3, 4)));  // true — value equality

Fields are final; there are no setters. To "change" one, make a new record.

Adding validation

Java
public record Money(long paisa, Currency currency) {
    public Money {
        if (paisa < 0) {
            throw new IllegalArgumentException("Cannot be negative");
        }
    }

    public double toRupees() { return paisa / 100.0; }
}

Use records for DTOs, API responses, coordinates, value objects — anywhere the object is its data. Use a normal class when it has identity or mutable state.