ProgrammingVery hardTCS NQT Digital · Accenture Advanced
What does this print?
What does this print?
static StringBuilder f() {
StringBuilder sb = new StringBuilder("a");
try { sb.append("b"); return sb; }
finally { sb.append("c"); sb = new StringBuilder("z"); }
}
// main: System.out.print(f());- A. ab
- B. z
- C. abc
- D. abcz
Correct answer: C. abc
The return value is the reference to the original builder, saved before finally; finally mutates that same object (adds c) but reassigning sb does not change the saved reference.
More OOP with C++ and Java questions
- What is printed? java String a = "hi"; String b = new String("hi"); String c = b.intern(); System.out.print((a == b) + " " + (a == c) + "…
- What is printed? java static void f(Integer i) { System.out.print("I"); } static void f(long l) { System.out.print("L"); } static void…
- What is printed? java Integer a = 127, b = 127, c = 128, d = 128; System.out.print((a == b) + " " + (c == d) + " " + c.equals(d));
- What happens when this runs? java Integer n = null; boolean flag = false; Integer r = flag ? 1 : n; System.out.print(r);
- What is printed? java byte b = 10; b += 120; System.out.print(b + " " + (b >>> 1));
- What is printed? java try { try { throw new Exception("1"); } finally { throw new RuntimeException("2"); } } catch (Exception e) {…