In Java, the record keyword is used to declare a special class type that acts as a “data carrier” i.e. model class or POJO class. This keyword is added to the Java language since JDK 14.

Consider an example:

record Point(int x, int y) { }

The Java compiler will generate appropriate constructor, getters and setters for all fields, equals(), hashCode() and toString() methods for a record type. The record type Point above is equivalent to code the following class:

public class Point {
	private int x;
	private int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getX() {
		return this.x;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getY() {
		return this.y;
	}

	public boolean equals(Object obj) {
		// implement equals based on fields x and y
	}

	public int hashCode() {
		// implement hashCode based on fields x and y
	}

	public String toString() {
		// implement toString based on fields x and y
	}
}

So as you can see, with the new record type, you can save a lot of time when coding such POJO classes. You also avoid error-prone implementation of equals() and hashCode() if you do it by yourself.

The record type feature is under review in JDK 14 (preview) and it will be finalized in future JDK releases.

See all keywords in Java.

Other Java Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment