Java Tutorial
- Java - Home
- Java - Overview
- Java - History
- Java - Features
- Java vs C++
- Java Virtual Machine (JVM)
- Java - JDK vs JRE vs JVM
- Java - Hello World Program
- Java - Environment Setup
- Java - Basic Syntax
- Java - Variable Types
- Java - Data Types
- Java - Type Casting
- Java - Unicode System
- Java - Basic Operators
- Java - Comments
Java Control Statements
- Java - Loop Control
- Java - Decision Making
- Java - If-else
- Java - Switch
- Java - For Loops
- Java - For-Each Loops
- Java - While Loops
- Java - do-while Loops
- Java - Break
- Java - Continue
Object Oriented Programming
- Java - OOPs Concepts
- Java - Object & Classes
- Java - Class Attributes
- Java - Class Methods
- Java - Methods
- Java - Variables Scope
- Java - Constructors
- Java - Access Modifiers
- Java - Inheritance
- Java - Aggregation
- Java - Polymorphism
- Java - Overriding
- Java - Method Overloading
- Java - Dynamic Binding
- Java - Static Binding
- Java - Instance Initializer Block
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java - Inner Classes
- Java - Static Class
- Java - Anonymous Class
- Java - Singleton Class
- Java - Wrapper Classes
- Java - Enums
- Java - Enum Constructor
- Java - Enum Strings
Java Built-in Classes
Java File Handling
- Java - Files
- Java - Create a File
- Java - Write to File
- Java - Read Files
- Java - Delete Files
- Java - Directories
- Java - I/O Streams
Java Error & Exceptions
- Java - Exceptions
- Java - try-catch Block
- Java - try-with-resources
- Java - Multi-catch Block
- Java - Nested try Block
- Java - Finally Block
- Java - throw Exception
- Java - Exception Propagation
- Java - Built-in Exceptions
- Java - Custom Exception
Java Multithreading
- Java - Multithreading
- Java - Thread Life Cycle
- Java - Creating a Thread
- Java - Starting a Thread
- Java - Joining Threads
- Java - Naming Thread
- Java - Thread Scheduler
- Java - Thread Pools
- Java - Main Thread
- Java - Thread Priority
- Java - Daemon Threads
- Java - Thread Group
- Java - Shutdown Hook
Java Synchronization
- Java - Synchronization
- Java - Block Synchronization
- Java - Static Synchronization
- Java - Inter-thread Communication
- Java - Thread Deadlock
- Java - Interrupting a Thread
- Java - Thread Control
- Java - Reentrant Monitor
Java Networking
- Java - Networking
- Java - Socket Programming
- Java - URL Processing
- Java - URL Class
- Java - URLConnection Class
- Java - HttpURLConnection Class
- Java - Socket Class
- Java - Generics
Java Collections
Java Interfaces
- Java - List Interface
- Java - Queue Interface
- Java - Map Interface
- Java - SortedMap Interface
- Java - Set Interface
- Java - SortedSet Interface
Java Data Structures
Java Collections Algorithms
Advanced Java
- Java - Command-Line Arguments
- Java - Lambda Expressions
- Java - Sending Email
- Java - Applet Basics
- Java - Javadoc Comments
- Java - Autoboxing and Unboxing
- Java - File Mismatch Method
- Java - REPL (JShell)
- Java - Multi-Release Jar Files
- Java - Private Interface Methods
- Java - Inner Class Diamond Operator
- Java - Multiresolution Image API
- Java - Collection Factory Methods
- Java - Module System
- Java - Nashorn JavaScript
- Java - Optional Class
- Java - Method References
- Java - Functional Interfaces
- Java - Default Methods
- Java - Base64 Encode Decode
- Java - Switch Expressions
- Java - Teeing Collectors
- Java - Microbenchmark
- Java - Text Blocks
- Java - Dynamic CDS archive
- Java - Z Garbage Collector (ZGC)
- Java - Null Pointer Exception
- Java - Packaging Tools
- Java - Sealed Classes
- Java - Record Classes
- Java - Hidden Classes
- Java - Pattern Matching
- Java - Compact Number Formatting
- Java - Garbage Collection
- Java - JIT Compiler
Java Miscellaneous
- Java - Recursion
- Java - Regular Expressions
- Java - Serialization
- Java - Strings
- Java - Process API Improvements
- Java - Stream API Improvements
- Java - Enhanced @Deprecated Annotation
- Java - CompletableFuture API Improvements
- Java - Streams
- Java - Datetime Api
- Java 8 - New Features
- Java 9 - New Features
- Java 10 - New Features
- Java 11 - New Features
- Java 12 - New Features
- Java 13 - New Features
- Java 14 - New Features
- Java 15 - New Features
- Java 16 - New Features
Java APIs & Frameworks
Java Class References
- Java - Scanner Class
- Java - Arrays Class
- Java - Strings
- Java - Date & Time
- Java - ArrayList
- Java - Vector Class
- Java - Stack Class
- Java - PriorityQueue
- Java - LinkedList
- Java - ArrayDeque
- Java - HashMap
- Java - LinkedHashMap
- Java - WeakHashMap
- Java - EnumMap
- Java - TreeMap
- Java - The IdentityHashMap Class
- Java - HashSet
- Java - EnumSet
- Java - LinkedHashSet
- Java - TreeSet
- Java - BitSet Class
- Java - Dictionary
- Java - Hashtable
- Java - Properties
- Java - Collection Interface
- Java - Array Methods
Java Useful Resources
Java - Record
In Java 14, an exciting feature record was introduced as a preview feature. The record feature helps in creating immutable data objects. In the Java 15 version, record types were enhanced further. In Java 14 and 15, in order to use a record, a flag --enable-preview has to be passed. From Java 16 onwards, this flag is not required as the record is a standard part of JDK.
Purpose of a Java Record
The prime purpose of a record is to create a data object or a POJO which is used to carry data in application program flow. In a multi-tier program, Domain/Model objects store the data captured from the data source and then these model objects are passed further to the application/UI layer to process the data and vice versa where UI/Application stores data in data objects and then pass these objects to Data layer to populate data sources.
As these data objects contain a lot of fields, developers are required to write a lot of setter/getter methods, parameterized constructors, overridden equals methods, and hashcode methods. In such a scenario, the record comes to the rescue as it provides most of the boilerplate code and the developer can focus on required functionalities only.
Features of Java Record
Following are the features of the record which makes the record an exciting feature:
- Record objects have an implicit constructor with all the parameters as field variables.
- Record objects have implicit field-getter methods for each field variable.
- Record objects have implicit field setter methods for each field variable.
- Record objects have an implicit sensible implementation of hashCode(), equals(), and toString() methods.
- With Java 15, native methods cannot be declared in records.
- With Java 15, implicit fields of record are not final and modification using reflection will throw IllegalAccessException.
Example Without Using Java Record
Let's create a simple program without using record where we're creating a Student object and printing its details. The Student has three properties, id, name and className. In order to create a student, we've create a parameterized constructor, setter, getter methods, equals and hashcode methods. Thus our Student class is completed with nearly 60+ lines.
package com.tutorialspoint; public class Tester { public static void main(String args[]) { // create student objects Student student1 = new Student(1, "Mahesh", "XII"); Student student2 = new Student(2, "Sudhir", "XII"); // print the students System.out.println(student1); System.out.println(student2); // check if students are same boolean result = student1.equals(student2); System.out.println(result); // check if students are same result = student1.equals(student1); System.out.println(result); // get the hashcode System.out.println(student1.hashCode()); System.out.println(student2.hashCode()); } } class Student{ private int id; private String name; private String className; Student(int id, String name, String className){ this.id = id; this.name = name; this.className = className; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public String toString() { return "Student[id: " + id + ", name: " + name + ", class: " + className + "]"; } @Override public boolean equals(Object obj) { if(obj == null || !(obj instanceof Student) ) { return false; } Student s = (Student)obj; return this.name.equals(s.name) && this.id == s.id && this.className.equals(s.className); } @Override public int hashCode() { int prime = 19; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((className == null) ? 0 : className.hashCode()); result = prime * result + id; return result; } }
Let us compile and run the above program, this will produce the following result −
Student[id: 1, name: Mahesh, class: XII] Student[id: 2, name: Sudhir, class: XII] false true 371251946 288252156
Example Using Java Record
Let's recreate above program using record where we're creating a Student object as record and printing its details. The Student has three properties, id, name and className. Here you can see the difference, the complete Student class is replaced with one line of code as Student record.
package com.tutorialspoint; public class Tester { public static void main(String args[]) { // create student objects Student student1 = new Student(1, "Mahesh", "XII"); Student student2 = new Student(2, "Sudhir", "XII"); // print the students System.out.println(student1); System.out.println(student2); // check if students are same boolean result = student1.equals(student2); System.out.println(result); // check if students are same result = student1.equals(student1); System.out.println(result); // get the hashcode System.out.println(student1.hashCode()); System.out.println(student2.hashCode()); } } record Student(int id, String name, String className) {}
Let us compile and run the above program, this will produce the following result −
Student[id: 1, name: Mahesh, class: XII] Student[id: 2, name: Sudhir, class: XII] false true 371251946 288252156
We can add custom methods in records as well. But generally it is not required.
Java Record for Sealed Interfaces
As records are final by default and can extend interfaces. We can define sealed interfaces and let records implement them for better code management.
Example: Use of Java Record for Sealed Interfaces
Consider the following example −
package com.tutorialspoint; public class Tester { public static void main(String[] args) { Person employee = new Employee(23, "Robert"); System.out.println(employee.id()); System.out.println(employee.name()); } } sealed interface Person permits Employee, Manager { int id(); String name(); } record Employee(int id, String name) implements Person {} record Manager(int id, String name) implements Person {}
Let us compile and run the above program, this will produce the following result −
23 Robert
Overriding Methods of Java Records
We can override a record method implementation easily and provide our own implementation.
Example: Override Java Record Methods
Consider the following example −
package com.tutorialspoint; public class Tester { public static void main(String args[]) { // create student objects Student student = new Student(1, "Mahesh", "XII"); System.out.println(student); } } record Student(int id, String name, String className) { public String toString() { return "Id: " + id + ", Name: " + name + ", class: " + className ; } }
Let us compile and run the above program, this will produce the following result −
Id: 1, Name: Mahesh, class: XII