SteelReed

Search

Search posts, questions…

Java CoreQuestion 14 / 43

Junior

Why is String immutable? What is the string pool, and how many objects does new String("abc") create?

Short answer

A String cannot be changed (immutable): every "change" creates a new string. That is why equal strings can be shared in the string pool.

first time, if absentevery executionintern()s1, s2 = literal 'abc''abc' in poolnew String('abc')new object on heap

3 points to say:

  1. Immutable means safe sharing and no locks for many threads.
  2. new String("abc") creates at most 2 objects.
  3. s = s + "d" creates a new string, the old one is untouched.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.