Java Tutorial

Java Records

A record is a compact immutable data carrier — the compiler writes the constructor, accessors, equals, hashCode, and toString for you.

Declare a record

Write the components in the header. Each becomes a private final field plus a public accessor named like the component (no get prefix). Records are implicitly final.

Example

record Point(int x, int y) {}

public class Main {
  public static void main(String[] args) {
    Point p = new Point(3, 4);
    System.out.println(p.x() + "," + p.y());
    System.out.println(p);
  }
}

equals and hashCode

Two records with the same component values compare equal. That makes them natural map keys and set members when the identity is the data itself.

Example

record Point(int x, int y) {}

public class Main {
  public static void main(String[] args) {
    Point a = new Point(1, 2);
    Point b = new Point(1, 2);
    System.out.println(a.equals(b));   // true
    System.out.println(a == b);        // false — different objects
  }
}

Compact constructor for validation

A compact constructor has no parameter list — it runs after fields are assigned from the header, and is the place to validate or normalize.

Example

record Person(String name, int age) {
  Person {
    if (age < 0) throw new IllegalArgumentException("age");
    name = name.trim();
  }
}

public class Main {
  public static void main(String[] args) {
    Person p = new Person("  Ada  ", 36);
    System.out.println(p.name() + " " + p.age());
  }
}

Prefer records for plain “hold these fields together” types. Reach for a full class when you need inheritance, mutable state, or rich behavior beyond data.

Nested in lists and maps

Records shine as elements of collections — readable toString, value-based equality, little boilerplate.

Example

import java.util.List;

record Item(String name, double price) {}

public class Main {
  public static void main(String[] args) {
    List cart = List.of(
        new Item("Tea", 2.5),
        new Item("Cake", 4.0)
    );
    for (Item i : cart) {
      System.out.println(i.name() + " " + i.price());
    }
  }
}

Record components are immutable references, but if a component is a mutable list, the list contents can still change. Prefer immutable component types.

Try It Yourself

Exercise: Define record Book(String title, int pages), create one instance, and print title and pages via the accessors.

Show solution
record Book(String title, int pages) {}

Book b = new Book("Dune", 412);
System.out.println(b.title() + " (" + b.pages() + ")");

Accessors match component names: title() and pages(), not getters.

Key Takeaways

  • Records are concise immutable data carriers with generated equals, hashCode, and toString.
  • Accessors are named after components: x(), not getX().
  • Use a compact constructor to validate or normalize inputs.
  • Choose a class instead when you need mutability or inheritance.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Chemistry

Immutable mole pair

A record is a compact immutable data carrier. Concentration and volume travel together with accessors generated for you.

n = cV

Example

record Solution(double conc, double vol) {
  double moles() { return conc * vol; }
}

public class Main {
  public static void main(String[] args) {
    System.out.println(new Solution(0.1, 0.25).moles());
  }
}

FAQ: Java Records

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java records examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java records in this Java Java lesson (Java Records).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.