Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

What is printed? (Java String vs StringBuilder)

What is printed? (Java String vs StringBuilder)
String s = "ab";
s.concat("cd");
StringBuilder sb = new StringBuilder("ab");
sb.append("cd");
System.out.println(s + " " + sb + " " + s.length() + sb.length());
  1. A. abcd abcd 44
  2. B. ab abcd 24
  3. C. ab abcd 6
  4. D. abcd abcd 8

Correct answer: B. ab abcd 24

Strings are immutable: s.concat("cd") returns a new string that is discarded, so s stays "ab". StringBuilder.append mutates in place. In the + chain, s.length() + sb.length() are joined as strings after the preceding string, giving "2" then "4" → "24", not 6.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic