record ExamplesUse the record keyword to create lightweight classes that has multiple fields with an optional custom constructor.
This page was last reviewed on Jan 21, 2024.
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.
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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 21, 2024 (new).
© 2007-2024 Sam Allen.