What is the output of the following code snippet involving a Java Record?

Java MCQ: What is the output of the following code snippet involving a Java Record?

public record Point(int x, int y) {}

public class Main {
    public static void main(String[] args) {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(1, 2);
        System.out.println(p1.equals(p2));
    }
}

a) true
b) false
c) Compilation error
d) Runtime exception

Answer:

a) true

Explanation:

In this code snippet, a Point record is defined with two fields: x and y. Two instances of the Point record (p1 and p2) are created with the same values for x and y. The equals() method is called to compare p1 and p2.

Since records automatically generate an equals() method that compares the fields of the record, and because p1 and p2 have the same values for their fields (x and y), the equals() method returns true. Therefore, the output of the program is true.

This demonstrates one of the key features of records in Java: they provide an automatic implementation of equals() (and other methods like hashCode() and toString()), which is based on the fields declared in the record. This simplifies the process of comparing objects for equality and reduces the need for boilerplate code.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top