Home
Java
record Examples
Updated Jan 21, 2024
Dot Net Perls
Record. It is possible to add as many class types as necessary for a Java program. But for clarity of the code, and ease of maintenance, using records to reduce code size is possible.
class
With the record keyword, we can create a class with multiple fields. An optional constructor, with simplified syntax, can also be added for validation.
Example. This Java program defines 3 different records, and then creates one instance of each of them. Records can be defined at the class level, or locally within a method.
Part 1 The ShopEntry record has a String and an int, and it is defined within the Program class. We create an instance of ShopEntry.
Part 2 We define the ShopEntry2 record type locally, and create an instance of it. Records have special code to print out their values.
Part 3 We can specify a constructor on a record. We locally define ShopEntry3 and call toUpperCase in its constructor.
Constructor
String toLowerCase
public class Program { // Created in main. record ShopEntry (String name, int cost) {} public static void main(String[] args) { // Part 1: create new entry from class-level record. ShopEntry s = new ShopEntry("shoes", 200); System.out.println(s); // Part 2: use local record and create an instance of it. record ShopEntry2 (String name, int size) {} ShopEntry2 s2 = new ShopEntry2("pants", 40); System.out.println(s2); // Part 3: use local record with simplified constructor. record ShopEntry3 (String name, int id) { ShopEntry3 { name = name.toUpperCase(); id = id; } } ShopEntry3 s3 = new ShopEntry3("hat", 30); System.out.println(s3); } }
ShopEntry[name=shoes, cost=200] ShopEntry2[name=pants, size=40] ShopEntry3[name=HAT, id=30]
Some notes. For complicated types with many uses in a program, a class is probably worth creating. But if a type is only used in one place, and is simple, a record is a good option.
Tip We can also use the instanceof operator with records, to determine whether an Object is an instance of a certain record.
instanceof
Summary. Much like records in other object-oriented programming languages, the records in Java provide a lightweight, low-syntax class type. They can be used like classes in most ways.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 21, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen