ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
System.out.print(o1.equals(o2) + " " + (o1.hashCode() == o2.hashCode()));
}
}- A. false true
- B. true true
- C. false false
- D. true false
Correct answer: C. false false
Object's default equals() is identity comparison (==), and two separately constructed Objects are never the same reference, so equals() is false. Object's default hashCode() is typically derived from the object's identity/memory address, so two distinct objects (almost certainly) get different hash codes too.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("a"…
- What is printed? java class Key { final String name; Key(String n) { name = n; } @Override public boolean equals(Object o) { if (this ==…
- What is printed? java public class Main { public static void main(String[] args) { String a = "Hello"; String b = "hello"…
- What is printed? java class Base { Base() { System.out.print("Base "); } protected Base(int x) { System.out.print("Base(int) "); } } class…
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle-start "); } } class ElectricCar extends Vehicle { @Override…
- What is printed? cpp struct Base { Base() { cout << "Base "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1 "; } }; struct Mixin2 {…