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()));
}
}- A. true true
- B. true false (not guaranteed to match)
- C. false false
- 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
- What is printed? java class Base { void show() { System.out.print("Base"); } } class Sub extends Base { void show() {…
- What is printed? cpp struct Animal { virtual std::string sound() const = 0; void makeSound() const { cout << sound(); } virtual ~Animal()…
- What is printed? java class Base { Base() { System.out.print("Base-ctor "); } static { System.out.print("Base-static "); } } class Sub…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct Mid : Base { }; struct Leaf : Mid { void f() override {…
- What is printed? java public class Main { static class Base { public String toString() { return "Base"; } public boolean equals(Object o)…
- What is printed? cpp template <typename T> T maxVal(T a, T b) { return a > b ? a : b; } int main() { cout << maxVal(3, 7) << " " <<…