ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Box {
int value;
Box(int v) { value = v; }
}
public class Main {
public static void main(String[] args) {
Box b1 = new Box(5);
Box b2 = new Box(5);
System.out.print(b1.equals(b2) + " " + (b1 == b2));
}
}- A. true false
- B. true true
- C. false false
- D. false true
Correct answer: C. false false
Box never overrides equals(), so it inherits Object.equals(), which is purely identity comparison (==). b1 and b2 are two distinct objects, so both b1.equals(b2) and b1 == b2 are false, regardless of having the same value field.
More OOP with C++ and Java questions
- Which statement about overriding equals() correctly describes the contract that must hold?
- What is printed? java class Animal { String name; Animal(String n) { name = n; } @Override public boolean equals(Object o) { if (!(o…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; int b = 127; System.out.print(a == b)…
- What is printed? java public class Main { public static void main(String[] args) { String s1 = "java"; String s2 = "java".intern(); String…
- What is printed? java public class Main { public static void main(String[] args) { String s = "hello"; String t = s; t = t.concat("…
- What is printed? java public class Main { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object()…