These are the notes for Java episode 24. Episode 23 ended with a typo: a book's status stored as the String "AVIALABLE", which compiled perfectly and made the book vanish from every search. Today you make that typo impossible with an enum, a type with a fixed list of values: comparing with ==, values(), ordinal(), name(), valueOf(), switch, and enums with fields, constructors and methods (Indian train coaches with fares). Then you shrink a 30-line data class into one line with a record: free accessors, equals, hashCode and toString, immutability, and validation in a compact constructor. Every example was run with javac 21.
Part 1: enums
The problem: one typo, one missing book
A library stores each book's status as a String. A returned book gets a status with two letters swapped:
public class Main {
public static void main(String[] args) {
String[] status = { "AVAILABLE", "AVAILABLE", "ISSUED" };
status[2] = "AVIALABLE"; // the book came back
int count = 0;
for (String s : status) {
if (s.equals("AVAILABLE")) count++;
}
System.out.println("Available books: " + count);
}
}
Available books: 2
All three books are on the shelf, but only two are counted, and nothing complained. To the compiler, any text in quotes is a valid String.
Second attempt: int constants
Older Java code used numbered constants:
public class Main {
static final int AVAILABLE = 0;
static final int ISSUED = 1;
static final int LOST = 2;
public static void main(String[] args) {
int status = ISSUED;
status = 7;
System.out.println("Status: " + status);
}
}
Status: 7
A typo in a constant's name would be caught, but status is just an int, so 7 (meaningless) compiles too, and printing shows a number instead of a word.
Why both fail: String and int allow far more values than we want. We need a type that allows only these three.
Real-life example: a fixed menu of choices
| In real life | In Java |
|---|---|
| A traffic light: red, yellow, green, never purple | enum Light { RED, YELLOW, GREEN }: only these values exist |
| Lift buttons G, 1, 2, 3: you can't press 7 | Status.AVIALABLE is a compile error |
| A thali menu where each item has a price | enum values can carry data: SLEEPER(500) |
The enum
An enum (short for enumeration, a list you can count through) is a special kind of class with a fixed set of objects, listed at the top:
enum Status { AVAILABLE, ISSUED, LOST }
public class Main {
public static void main(String[] args) {
Status[] status = { Status.AVAILABLE, Status.AVAILABLE, Status.ISSUED };
status[2] = Status.AVIALABLE;
System.out.println(status[2]);
}
}
Main.java:6: error: cannot find symbol
status[2] = Status.AVIALABLE;
^
symbol: variable AVIALABLE
location: class Status
1 error
- The typo is caught at compile time.
- A
Statusvariable can hold onlyAVAILABLE,ISSUED,LOST, ornull. There is no way to write "7". - Enum values are constants, so they're written in UPPER_CASE.
What an enum can do
enum Status { AVAILABLE, ISSUED, LOST }
public class Main {
public static void main(String[] args) {
Status[] status = { Status.AVAILABLE, Status.AVAILABLE, Status.ISSUED };
status[2] = Status.AVAILABLE;
int count = 0;
for (Status s : status) {
if (s == Status.AVAILABLE) count++;
}
System.out.println("Available books: " + count);
for (Status s : Status.values()) {
System.out.println(s.ordinal() + " " + s.name());
}
Status s = Status.valueOf("LOST");
switch (s) {
case AVAILABLE -> System.out.println("On the shelf");
case ISSUED -> System.out.println("With a reader");
case LOST -> System.out.println("Charge a fine");
}
System.out.println(Status.valueOf("lost"));
}
}
Available books: 3
0 AVAILABLE
1 ISSUED
2 LOST
Charge a fine
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Status.lost
at java.base/java.lang.Enum.valueOf(Enum.java:293)
at Status.valueOf(Main.java:1)
at Main.main(Main.java:21)
| Feature | What it does | Example |
|---|---|---|
== |
Compare enum values (safe: each value is a single object) | s == Status.AVAILABLE |
values() |
Array of all values, in declaration order | Status.values() |
ordinal() |
Position, counting from 0 | ISSUED.ordinal() is 1 |
name() / toString() |
The value's name as text | "LOST" |
valueOf(String) |
Text to enum value; exact, case-sensitive match | Status.valueOf("LOST") |
switch |
Cases use the bare names, no Status. needed |
case LOST -> ... |
Notes:
valueOf("lost")throwsIllegalArgumentException. Convert user input first:Status.valueOf(input.trim().toUpperCase()).- Prefer
==overequalsfor enums:==also works when the variable isnull(it's justfalse), whiles.equals(...)on a nullsthrowsNullPointerException: Cannot invoke "Status.equals(Object)" because "<local1>" is null. - A switch expression (one that returns a value) must cover every value: leaving out
LOSTgiveserror: the switch expression does not cover all possible input values. That's another typo-catcher: add a fourth status later and the compiler points to every switch that forgot it. - Don't store
ordinal()in files or databases: inserting a new value in the middle shifts every number. Storename()instead.
Enums with fields, constructors and methods
An enum is really a class, so its values can carry data. Indian train coaches with a fare per person:
enum Coach {
SLEEPER(500), AC3(1200), AC2(1800);
final int fare;
Coach(int fare) {
this.fare = fare;
}
int fareFor(int people) {
return fare * people;
}
}
public class Main {
public static void main(String[] args) {
for (Coach c : Coach.values()) {
System.out.println(c + ": " + c.fareFor(4));
}
}
}
SLEEPER: 2000
AC3: 4800
AC2: 7200
SLEEPER(500)calls the enum's constructor with500. The list of values must come first, ending with;when more code follows.- The fare lives with the coach, instead of in a separate
if-elsechain somewhere else. - An enum constructor is always private: nobody can add a value at runtime.
Coach mine = new Coach(900);
Main.java:18: error: enum classes may not be instantiated
Coach mine = new Coach(900);
^
1 error
The list at the top is the complete list. (Enums can also implement interfaces, and every enum automatically extends java.lang.Enum, so it can't extend another class.)
Part 2: records
The problem: a class that only carries data
A library member is just data: a name and a phone. Done properly (episodes 17 and 22), that class needs private final fields, a constructor, an accessor per field, equals, hashCode and toString: about 30 lines, with every field repeated five times. Add an email field and you must update all of them; forget equals and you get a silent bug.
The record
record Member(String name, String phone) { }
From that one line, Java writes:
| Generated | For Member(String name, String phone) |
|---|---|
private final fields |
name, phone |
| A canonical constructor | Member(String name, String phone) |
Accessors (no get) |
name(), phone() |
equals / hashCode |
compare every component |
toString |
Member[name=Asha, phone=9876543210] |
The values in the brackets are called the record's components. Records arrived in Java 16. A record is implicitly final (can't be extended) and extends java.lang.Record.
record Member(String name, String phone) { }
public class Main {
public static void main(String[] args) {
Member a = new Member("Asha", "9876543210");
Member b = new Member("Asha", "9876543210");
System.out.println(a);
System.out.println(a.name());
System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()));
}
}
Member[name=Asha, phone=9876543210]
Asha
true true
Records are immutable
a.name = "Ravi";
Main.java:10: error: name has private access in Member
a.name = "Ravi";
^
1 error
The fields are private and final, and there are no setters. A record can't change after it's created: it's immutable, like String. To "change" one, create a new record: new Member("Ravi", a.phone()). Immutable objects are safe to share and make perfect HashMap keys and HashSet items.
Validation with a compact constructor
record Member(String name, String phone) {
Member {
if (phone.length() != 10)
throw new IllegalArgumentException("phone must have 10 digits: " + phone);
}
}
public class Main {
public static void main(String[] args) {
Member a = new Member("Asha", "9876543210");
System.out.println(a);
Member b = new Member("Ravi", "12345");
System.out.println(b);
}
}
Member[name=Asha, phone=9876543210]
Exception in thread "main" java.lang.IllegalArgumentException: phone must have 10 digits: 12345
at Member.<init>(Main.java:4)
at Main.main(Main.java:12)
A compact constructor is the record's name followed directly by { }, with no parameter list. Your checks run first, then Java assigns the fields. A bad member can never exist. (throw is covered properly in episode 27.)
What a record can have: methods, static fields and methods, compact or extra constructors, and it can implement interfaces. What it can't have: extra instance fields or setters:
record Member(String name, String phone) {
int visits = 0;
}
Main.java:2: error: field declaration must be static
int visits = 0;
^
(consider replacing field with record component)
1 error
Class vs record: when to use which
| Use a record when... | Use a normal class when... |
|---|---|
| the object just carries data | the object has changing state (a bank balance) |
| equality means "same values" | identity matters (two accounts with equal fields are still different) |
| it should be immutable | it needs setters or inheritance |
| examples: a point, a member, a transaction, a search result | examples: an account, a game player, a shopping cart |
What you just invented
| Problem | Fix |
|---|---|
| A String status lets typos through | enum Status { AVAILABLE, ISSUED, LOST } |
An int status allows 7 |
enum: only listed values exist |
| Values that need data (a fare) | enum fields + constructor |
| 30 lines of boilerplate per data class | record Member(String name, String phone) { } |
| Bad data in a record | compact constructor |
Next: you now know classes, objects, encapsulation, inheritance, polymorphism, abstract classes, interfaces, final, Object, nested classes, enums and records: the whole object-oriented toolbox. Episode 25 uses all of it in one project: a bank management system.
Common mistakes (and the real error messages)
| Mistake | Real message | Why | Fix |
|---|---|---|---|
| A value not in the enum | error: cannot find symbol / symbol: variable AVIALABLE / location: class Status |
only listed values exist | Status.AVAILABLE |
valueOf with the wrong case |
IllegalArgumentException: No enum constant Status.lost |
exact, case-sensitive match | valueOf(input.toUpperCase()) |
new on an enum |
error: enum classes may not be instantiated |
the list is fixed | add the value to the enum |
| Switch expression missing a value | error: the switch expression does not cover all possible input values |
every value needs a case | add the case (or default) |
s.equals(...) when s is null |
NullPointerException: Cannot invoke "Status.equals(Object)" because "<local1>" is null |
method call on null | compare with == |
| Assigning a record field | error: name has private access in Member |
records are immutable | create a new record |
| Extra instance field in a record | error: field declaration must be static / (consider replacing field with record component) |
records hold only components | add it as a component |
Mini project: library books with an enum status and a record
import java.util.HashSet;
enum Status {
AVAILABLE("On the shelf"), ISSUED("With a reader"), LOST("Fine: Rs 500");
private final String label;
Status(String label) { this.label = label; }
String label() { return label; }
}
record Book(String isbn, String title, Status status) {
Book {
if (title.isBlank()) throw new IllegalArgumentException("title is empty");
}
Book issue() {
return new Book(isbn, title, Status.ISSUED);
}
}
public class Main {
public static void main(String[] args) {
Book a = new Book("978-81", "Java Basics", Status.AVAILABLE);
Book b = a.issue();
System.out.println(a);
System.out.println(b);
System.out.println(b.status().label());
HashSet<Book> shelf = new HashSet<>();
shelf.add(a);
shelf.add(new Book("978-81", "Java Basics", Status.AVAILABLE));
System.out.println("Books on shelf: " + shelf.size());
int[] count = new int[Status.values().length];
for (Book x : new Book[] { a, b, b }) count[x.status().ordinal()]++;
for (Status s : Status.values()) System.out.println(s + ": " + count[s.ordinal()]);
}
}
Book[isbn=978-81, title=Java Basics, status=AVAILABLE]
Book[isbn=978-81, title=Java Basics, status=ISSUED]
With a reader
Books on shelf: 1
AVAILABLE: 1
ISSUED: 2
LOST: 0
issue() doesn't change the book (records are immutable); it returns a new one. The HashSet keeps one copy because the record's equals and hashCode compare all components.
Practice
- Write
enum Daywith a methodisWeekend(). - Write
enum PizzaSize { SMALL(199), MEDIUM(349), LARGE(499) }with a price, and print the total for 3 large pizzas. - Why is
Status.valueOf(scanner.next())risky, and how do you make it safer?
Solutions
1.
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN;
boolean isWeekend() { return this == SAT || this == SUN; }
}
public class Main {
public static void main(String[] args) {
for (Day d : Day.values()) System.out.println(d + " " + d.isWeekend());
}
}
MON false
TUE false
WED false
THU false
FRI false
SAT true
SUN true
2. Add final int price; PizzaSize(int price) { this.price = price; } and print PizzaSize.LARGE.price * 3, which is 1497.
3. The user may type lost or Lost or a word that isn't a status, and valueOf throws IllegalArgumentException. Use input.trim().toUpperCase(), and handle bad input with try/catch (episode 26).
Quick quiz
enum Size { SMALL, MEDIUM, LARGE }
record Chai(Size size, int sugar) { }
// in main:
Chai a = new Chai(Size.LARGE, 2);
Chai b = new Chai(Size.LARGE, 2);
System.out.println(a.size().ordinal() + " " + a.equals(b));
A) 3 false B) 2 true C) 2 false D) LARGE true
Answer
B. ordinal() counts from 0, so LARGE is 2. Records get equals for free, comparing every component, so a.equals(b) is true.
2 true
Interview questions
- What is an enum? A special class with a fixed set of named instances; it gives type safety for values like days, statuses, sizes.
- Why compare enums with
==? Each enum value is a single object (a singleton), so reference equality is correct, faster, and null-safe. - Can an enum have a constructor, fields and methods? Yes; the constructor is implicitly private and is called once per value.
- Can an enum extend a class? No, every enum implicitly extends
java.lang.Enum. It can implement interfaces. - What do
values(),ordinal()andvalueOf()do? All values in order; a value's position from 0; text to enum (throwsIllegalArgumentExceptionif no match). - What is a record? A concise, immutable data-carrier class (Java 16+) whose fields, constructor, accessors,
equals,hashCodeandtoStringare generated from its components. - Can a record have setters or extra instance fields? No. It can have methods, static members, extra constructors and a compact constructor.
- What is a compact constructor? A record constructor without a parameter list, used to validate or normalise components before they're assigned.
- Record vs class with Lombok/hand-written boilerplate? A record is built into the language, immutable and final; use a class when you need mutable state or inheritance.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Enum | A type with a fixed list of values | enum Status { AVAILABLE, ISSUED, LOST } |
| Enum constant | One value of an enum | Status.ISSUED |
| Enumeration | A list you can count through, item by item | the days of the week |
| Type safety | The compiler stops values of the wrong type | status = 7 can't compile for a Status |
values() |
All enum values, in order | Status.values() |
ordinal() |
A value's position, from 0 | LOST.ordinal() is 2 |
name() |
A value's name as a String | "LOST" |
valueOf() |
Converts text to an enum value | Status.valueOf("LOST") |
| Switch expression | A switch that returns a value; must cover every case |
String m = switch (s) { ... }; |
| Overdraft (preview) | Going below zero in a current account (episode 25) | minBalance() = -5000 |
| Boilerplate | Repetitive code you must write but that adds no new idea | getters, equals, hashCode |
| Record | A one-line immutable data class | record Member(String name, String phone) { } |
| Component | A value listed in a record's header | name, phone |
| Accessor | A method that returns a component | a.name() |
| Immutable | Can't change after creation | String, records |
| Compact constructor | A record constructor with no parameter list, for checks | Member { if (...) throw ...; } |
| Canonical constructor | The constructor taking all components | new Member("Asha", "98...") |
Summary
- Strings and ints allow wrong values; an enum allows only its listed values, so typos become compile errors.
- Compare enums with
==; usevalues(),ordinal(),name(),valueOf()(case-sensitive), andswitch. - Enums are classes: they can have fields, constructors and methods (
SLEEPER(500)), but can't be created withnew. - A record is a data class in one line: Java writes the fields, constructor, accessors,
equals,hashCodeandtoString. - Records are immutable; validate data in a compact constructor.
- Next: every OOP idea working together. Episode 25: OOP project: a bank management system.