ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
// in main:
String s = "hello";
s.concat(" world");
System.out.println(s);
String t = s.concat(" world");
System.out.println(t);
  1. A. hello world then hello world
  2. B. hello then hello world
  3. C. hello world then hello
  4. D. hello then hello

Correct answer: B. hello then hello world

Strings are immutable: s.concat(" world") returns a NEW string without modifying s, so the ignored first call changes nothing, and the first println still prints "hello". The second call captures the returned new string into t, so the second println prints "hello world".

More OOP with C++ and Java questions

Exams that ask this topic