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());- A. abcd abcd 44
- B. ab abcd 24
- C. ab abcd 6
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (counting sort on small values) python a = [4, 1, 3, 4, 2, 1, 0, 4] cnt = [0] 5 for x in a: cnt[x] += 1 for i in range(1…
- How many swaps does this bubble sort make, and how many passes run? python a = [5, 1, 4, 2, 8] swaps = passes = 0 for i in range(len(a)…
- Insertion sort counts element shifts. What is printed? python a = [3, 7, 1, 5, 2] shifts = 0 for i in range(1, len(a)): key, j = a[i], i…
- Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index? python…
- Merge two sorted halves and count comparisons. What is printed? python L, R = [1, 4, 6, 9], [2, 3, 10] i = j = comps = 0; out = [] while i…
- What is printed? (Python list aliasing) python a = [1, 2, 3] b = a c = a[:] b.append(4) c.append(5) print(a, len(b), len(c))