Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Records: A Whole Data Class in One Line

record Order(String id, String customer, double total) replaces a 30-line class: toString, accessors like customer(), equals and hashCode come free. A Shipment changes by copying, an Invoice compact constructor rejects -50 and tidies " inv-2031 ", and an Account stays a class.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Declare a record and use its accessors, equals, hashCode and toString
  • Describe what the compiler generates for a record
  • Change a record by building a new copy instead of using setters
  • Validate and tidy input in a compact constructor, and choose a record or a class

Before you start

  • Java final and immutable objects
  • Java equals and hashCode

Think of a record as a shipping label. The details are printed once, and after that nobody changes them. A record holds a fixed set of values, and Java writes the boilerplate for you.

A whole class in one line

The project's PlainOrder is the class you'd write by hand to hold three values: fields, a constructor, getters, equals, hashCode and toString, about 30 lines. Only the fields say anything new. A record says just that part:

package org.studyeasy.s05l01;

public class Ex01_OrderRecord {
    // Fields, constructor, accessors, equals, hashCode, toString
    record Order(String id, String customer, double total) {}

    public static void main(String[] args) {
        Order order = new Order("A-1001", "Priya", 749.50);
        System.out.println(order);              // toString for free

        // Accessors are named after the fields: no "get"
        System.out.println(order.customer() + " pays " + order.total());

        Order same = new Order("A-1001", "Priya", 749.50);
        System.out.println(order.equals(same));   // same values
        System.out.println(order.hashCode() == same.hashCode());
        System.out.println(order == same);        // two objects
    }
}
Order[id=A-1001, customer=Priya, total=749.5]
Priya pays 749.5
true
true
false

Printing shows every component by name, though we never wrote toString. There are no getters; the accessors are named after the components, so it's customer(), not getCustomer(). equals compares the values, so two orders with the same values are equal and have equal hash codes. == is still false: they're two objects. And order.total = 0; doesn't compile, because the field is final.

From one line, record Order(String id, String customer, double total), the compiler writes a final class that extends Record, one private final field per component, a constructor taking all three in header order, toString, hashCode and equals, and one accessor per component such as customer(). record Order(String id, String customer, double total) final class Order extends Record private final String id, customer; private final double total; Order(String, String, double) toString() hashCode() equals() id() customer() total() you write the header, the compiler writes the rest
What javap shows inside the compiled record.

Open the compiled record with the javap tool and you see it: a final class that extends Record (so it can't have another parent), one private final field per component, a constructor taking them in header order, the three methods, and the accessors.

No setters: a change is a copy

record Shipment(String trackingId, String city, String status) {
    Shipment withStatus(String newStatus) {   // no setters: copy
        return new Shipment(trackingId, city, newStatus);
    }
}

Shipment placed = new Shipment("TRK-42", "Pune", "PLACED");
Shipment shipped = placed.withStatus("SHIPPED");
System.out.println(placed);     // the original is untouched
System.out.println(shipped);

// Built-in equals + hashCode: a Set spots the repeat
Set<Shipment> seen = new HashSet<>();
seen.add(shipped);
seen.add(new Shipment("TRK-42", "Pune", "SHIPPED"));
System.out.println("In the set: " + seen.size());
Shipment[trackingId=TRK-42, city=Pune, status=PLACED]
Shipment[trackingId=TRK-42, city=Pune, status=SHIPPED]
In the set: 1

A record can't be changed, so withStatus (our own method) builds a second Shipment, copying the tracking id and city and putting in the new status. placed is untouched. The built-in equals and hashCode let a HashSet spot the second, equal shipment, so the set holds one.

Compact constructor: guard the data

record Invoice(String number, String customer, double amount) {
    Invoice {                                // compact: no (...)
        if (amount <= 0)
            throw new IllegalArgumentException("amount must be > 0");
        number = number.trim().toUpperCase();   // tidy the input
    }                                 // fields are assigned here
}

Invoice inv = new Invoice(" inv-2031 ", "Mei Lin", 1899.0);
System.out.println(inv);               // number already tidied
System.out.println(inv.number().equals("INV-2031"));
try {
    new Invoice("INV-2032", "Tom Walker", -50);
} catch (IllegalArgumentException e) {
    System.out.println("Rejected: " + e.getMessage());
}
Invoice[number=INV-2031, customer=Mei Lin, amount=1899.0]
true
Rejected: amount must be > 0

Invoice { ... } with no brackets is a compact constructor. It runs in three stages: check, tidy, then assign. 1899 passes the check, the number loses its spaces and becomes capitals, and the fields are assigned at the closing brace, so the tidied number is what's stored. -50 stops at the check: the throw means no record is built. Writing this.amount = amount; inside it doesn't compile; Java does the assigning.

Facts are records, change is a class

record Txn(String type, double amount) {}  // a fact: fixed

static class Account {                     // it changes: a class
    double balance;
    final List<Txn> history = new ArrayList<>();

    void deposit(double amount) {
        balance += amount;                        // state moves
        history.add(new Txn("DEPOSIT", amount));  // facts pile up
    }
}
Balance: 750.0
Txn[type=DEPOSIT, amount=500.0]
Txn[type=DEPOSIT, amount=250.0]

Depositing 500 and then 250 moves the balance to 750, and each deposit adds a Txn to the history. The balance changed; the transactions were never edited. Ask one question: will this value change? No means a record (Order, Invoice, Txn), yes means a class. Turn Account into a record and balance += a fails: cannot assign a value to final variable balance.

Recap

FeatureExample
Declarerecord Order(String id, String customer, double total) {}
Accessorsorder.customer(), no "get"
Free methodstoString, equals, hashCode by value
Changebuild a copy: withStatus("SHIPPED")
Validatecompact constructor: Invoice { ... }

Records pair well with sealed classes and record patterns, coming next.

Keep going in Java · 41 of 79

Previous
Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
Next post
Java Sealed Classes and Interfaces
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • A whole class in one line
  • No setters: a change is a copy
  • Compact constructor: guard the data
  • Facts are records, change is a class
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.