ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        String s = "hello";
        String t = s;
        t = t.concat(" world");
        System.out.print(s + " | " + t);
    }
}
  1. A. hello | hello world
  2. B. hello world | hello world
  3. C. hello | hello
  4. D. Compilation error: t is already assigned to s

Correct answer: A. hello | hello world

Strings are immutable: concat() returns a brand-new String rather than modifying in place. t is reassigned to point at that new string, but s still refers to the original, unmodified "hello".

More OOP with C++ and Java questions

Exams that ask this topic