ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
class P {
int x;
P(int x) { this.x = x; }
public boolean equals(Object o) {
return o != null && getClass() == o.getClass() && ((P) o).x == x;
}
public int hashCode() { return x; }
}
class Q extends P { Q(int x) { super(x); } }
// in main:
System.out.print(new P(1).equals(new Q(1)) + " " + new Q(1).equals(new Q(1)));- A. false true
- B. true true
- C. false false
- D. true false
Correct answer: A. false true
An equals based on getClass() treats objects of different runtime classes as unequal, even a subclass that adds nothing. instanceof would have returned true for P vs Q.
More OOP with C++ and Java questions
- What is printed? java Boolean b1 = true, b2 = true; Character c1 = 'a', c2 = 'a'; Short s1 = 100, s2 = 100; System.out.print((b1 == b2) +…
- What is printed? java List<Integer> l = Arrays.asList(3, 1, 2); Collections.sort(l); System.out.print(l + " "); l.clear();
- What is printed? java List<String> l = new ArrayList<>(List.of("a", "b", "c")); ListIterator<String> it = l.listIterator(); while…
- What is printed? java System.out.print("a.b.c".split(".").length + " " + "a.b.c".split(".").length);
- What is printed? java System.out.print("a.b".replace(".", "x") + " " + "a.b".replaceAll(".", "x"));
- What is printed? java List<Integer> src = List.of(1, 2); List<Integer> dst = new ArrayList<>(5); Collections.copy(dst, src)…