ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
Long l = 127L; Integer i = 127; System.out.print(l.equals(127) + " "); System.out.print(l.equals(127L) + " "); System.out.print((l == 127) + " "); System.out.print(i.equals(l));
- A. true true true false
- B. true true true true
- C. false true false false
- D. false true true false
Correct answer: D. false true true false
equals on wrapper classes first checks the runtime type. l.equals(127) boxes the int 127 to an Integer, which is not a Long, so false. l.equals(127L) compares with a Long of equal value: true. l == 127 compares a Long with an int, which unboxes l and compares numerically: true. i.equals(l) is false for the same type reason. The values are equal everywhere; only the boxed types differ.
More OOP with C++ and Java questions
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("long "); } static void f(Integer x) {…
- What happens when this code runs? java List<String> strs = new ArrayList<>(); strs.add("a"); List raw = strs; raw.add(42)…
- What is printed? java final String a = "Ja"; String b = "Ja"; String x = a + "va"; String y = b + "va"; String z = y.intern()…
- What is printed? java class K { int id; K(int id) { this.id = id; } public boolean equals(Object o) { return o instanceof K && ((K) o).id…
- What happens when this code runs? java Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0)…
- Which lines fail to compile? java short s = 1; s = s + 1; // L1 s += 1; // L2 char c = 'A'; c++; // L3 final int k = 10; byte b1 = k; //…