Master Java Records: Simplify Immutable Classes in Java 16+
This article explains the new Java 16 record keyword, showing how to declare records, their automatically generated methods, and how to add custom behavior, with clear code examples and testing tips for creating concise, immutable data classes.
Declaring a record class
Since Java 16, the record keyword can be used to define a class, offering a concise way to create a final class. record range(int start, int end) {} Records can be declared in three ways:
In a separate file: public record range(int start, int end) {} Inside another class:
public class DidispaceTest {
public record range(int start, int end) {}
}Inside a method:
public class DidispaceTest {
public void test() {
public record range(int start, int end) {}
}
}Record class details
A record automatically provides:
It is a final class.
Implementations of equals, hashCode, and toString.
All component fields are public and immutable.
The previous range class is equivalent to:
public final class range {
final int start;
final int end;
public range(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
range range = (range) o;
return start == range.start && end == range.end;
}
@Override
public int hashCode() {
return Objects.hash(start, end);
}
@Override
public String toString() {
return "range{" + "start=" + start + ", end=" + end + '}';
}
public int start() { return start; }
public int end() { return end; }
}To verify the generated methods, you can run a simple test:
@Test
public void test() {
range r = new range(100, 200);
log.info(r.toString());
range r2 = new range(100, 200);
log.info(String.valueOf(r.equals(r2)));
}Defining member functions
Records can also contain custom methods. For example, adding a distance calculation:
record range(int start, int end) {
int distance() {
return end - start;
}
}Usage:
range r = new range(100, 200);
int d = r.distance();For more Java new‑feature tutorials, see the free Java features series.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
