ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
// Java 16 or later
record P(int x, int y) { }
// in main:
P a = new P(1, 2), b = new P(1, 2);
System.out.print((a == b) + " " + a.equals(b) + " "
+ (a.hashCode() == b.hashCode()) + " " + a.x());- A. true true true 1
- B. false false false 1
- C. false true false 1
- D. false true true 1
Correct answer: D. false true true 1
Records get component-based equals and hashCode and an accessor method x(), but new still creates two distinct objects, so == is false.
More OOP with C++ and Java questions
- What happens when this is compiled? java class P { P(int x) { } P() { } } class C extends P { } // in main: C c = new C(5);
- What happens when C is compiled? java class P { static void s() { } } class C extends P { @Override static void s() { } }
- Which lazily-initialised singleton is thread-safe WITHOUT any explicit synchronization or volatile field?
- What is printed? java // static generic method of the main class: static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b)…
- What is printed? java class A { private int v = 1; boolean same(A other) { return v == other.v; } void set(A other) { other.v = 9; } } //…
- What is printed? cpp struct M { M(const char s) { cout << s; } }; struct S { M x, y; S() : y("Y"), x("X") { cout << "S"; } }; int main() {…