Java String allocation count: given String x = new String("xyz"); String y = "abc"; x = x + y; how many distinct String objects are created?

Difficulty: Easy

Correct Answer: 4

Explanation:


Introduction / Context:
This problem assesses your understanding of String creation via literals, the new operator, and concatenation. Counting allocations helps clarify immutability and compiler/runtime behaviors.


Given Data / Assumptions:

  • Literals: "xyz" and "abc" are interned in the string pool (2 objects).
  • new String("xyz") creates a distinct heap String that copies the literal (1 more object, total 3).
  • x = x + y creates a new result String containing "xyzabc" (1 more object, total 4). Temporary StringBuilder used internally is not a String object.


Concept / Approach:
Each literal creates or reuses a pooled String. The new expression always creates a new String object. Concatenation of two runtime Strings produces a fresh String containing the combined characters.


Step-by-Step Solution:
Literal creation: "xyz" and "abc".Heap allocation: new String("xyz").Concatenation result: "xyzabc".Total String objects: 4.


Verification / Alternative check:
Observe x == "xyz" is false after new String("xyz"), proving a distinct object. Use a profiler or logging constructors to confirm counts (conceptually).


Why Other Options Are Wrong:
2 or 3 undercount by missing either the new-heap copy or the concatenation result. 5 overcounts; the builder is not a String.


Common Pitfalls:
Confusing the string pool with heap objects created by new; assuming concatenation mutates an existing String (it cannot).


Final Answer:
4

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion