ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.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) + " " + (p1.hashCode() == p2.hashCode()));
    }
}
  1. A. true true
  2. B. true false (not guaranteed to match)
  3. C. false false
  4. D. false true

Correct answer: B. true false (not guaranteed to match)

equals() is overridden to compare by value, so p1.equals(p2) is true. hashCode() is NOT overridden, so Point falls back to Object's identity-based hashCode, which is extremely unlikely to match between two separately allocated objects — equals() says they're equal, but hashCode() breaks the required contract, so the two hash codes are not guaranteed (and practically will not) be equal.

More OOP with C++ and Java questions

Exams that ask this topic