01 / 21

String Immutability
in Java

Understand why Java Strings cannot be changed once created, how the String Pool works, and the performance implications of every concatenation.

Java

What Is a String in Java?

A String is a sequence of characters stored as an object on the heap. Unlike primitive types, Strings are instances of the java.lang.String class and have special treatment by the JVM.

Object Type
Strings are reference types, not primitives. Variables hold a reference to the String object in memory.
char[] Backed
Internally, a String wraps a private final char[] array (or byte[] in Java 9+). This array is never exposed.

What Does Immutable Mean?

An immutable object is one whose state cannot be modified after it is created. For Strings, this means:

1
No character replacement: You cannot change the character at index \( i \) of an existing String.
2
No in-place append: Concatenation always produces a new String object rather than modifying the original.
3
No length change: The internal array is final and its reference can never be reassigned.

Why Are Strings Immutable?

Security
Strings carry passwords, URLs, and class names. Immutability prevents malicious code from altering these values after validation.
Thread Safety
Immutable objects are inherently thread-safe: multiple threads can share the same String with no synchronization.
Caching
Because a String never changes, its hashCode can be computed once and cached, speeding up HashMap lookups.

The String Pool

The JVM maintains a special memory region called the String Pool (or intern pool). When you create a String literal, Java first checks the pool. If an identical String already exists, it returns a reference to the existing object instead of creating a new one.

STRING POOL (Heap) "Hello" "World" "Java" s1 = "Hello" s2 = "Hello" s3 = "World" STACK s1 == s2 is true

The Immutability Rule

String name = "Alice";
name.toUpperCase();  // returns "ALICE" but name is still "Alice"

name = name.toUpperCase();  // now name references the NEW "ALICE"

What Happens in Memory?

Step 1: String s = "Hi"; "Hi" s Step 2: s = s + "!"; "Hi" (orphaned) "Hi!" s The original "Hi" was NOT modified. A new object "Hi!" was created.

String vs StringBuilder

String StringBuilder
Mutability Immutable Mutable
Concatenation Creates new object each time Modifies internal buffer in place
Thread Safety Safe (immutable) Not safe
Performance (loops) \( O(n^2) \) with + operator \( O(n) \) amortized
Use When Few modifications Many modifications (loops)

The Performance Trap

Concatenating Strings in a loop with the + operator creates a new String object on every iteration. For \( n \) iterations, Java copies increasingly larger arrays, leading to \( O(n^2) \) total character copies.

// BAD: \( O(n^2) \) performance
String result = "";
for (int i = 0; i < 10000; i++) {
  result = result + "x";  // new object every iteration!
}
// GOOD: \( O(n) \) performance
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
  sb.append("x");  // same buffer, just grows
}
String result = sb.toString();

How to Apply This Knowledge

1
Identify the scope: Is the String modified inside a loop or only once or twice?
2
Count modifications: If \( n \leq 3 \) concatenations, plain String \( + \) is fine (compiler may optimize).
3
Choose the right tool: For loops or many appends, use StringBuilder. For thread-shared builders, use StringBuffer.
4
Use .equals(), not \( == \) for content comparison. Remember: \( == \) compares references, not characters.
5
Call .intern() when you want to force a runtime-created String into the pool for reference-level sharing.

Example 1: Reference Equality

String a = "cat";
String b = "cat";
String c = new String("cat");

System.out.println(a == b);   // ?
System.out.println(a == c);   // ?
System.out.println(a.equals(c)); // ?

Example 2: Concatenation Objects

Question: How many String objects are created by this code?

String s = "A" + "B" + "C";

Example 3: Loop Concatenation

Question: How many temporary String objects does this loop create?

String s = "";
for (int i = 0; i < 5; i++) {
  s = s + i;
}

The .intern() Method

Calling .intern() on a String checks the pool: if an equal String exists, it returns the pool's reference. Otherwise, it adds the String to the pool and returns that reference.

String a = new String("dog");
String b = a.intern();
String c = "dog";

System.out.println(a == b);  // false (a is on heap, b is pool ref)
System.out.println(b == c);  // true (both reference pool's "dog")

Common Mistakes

✕ Using \( == \) for Content
Using \( == \) to compare String values instead of .equals(). This compares references, not characters, and may give false negatives.
✕ Loop Concatenation
Concatenating with \( + \) inside a loop, creating \( O(n^2) \) temporary objects. Use StringBuilder for loops.
✕ Ignoring Return Values
Calling s.toUpperCase() without assigning the result. The original String is unchanged, and the new one is lost.

Summary Table

Concept Key Point
Immutability String content never changes after creation
String Pool Literals are cached and shared via the intern pool
\( == \) vs .equals() \( == \) checks reference; .equals() checks content
new String() Always creates a new heap object outside the pool
Concatenation in loops \( O(n^2) \) with \( + \); \( O(n) \) with StringBuilder
.intern() Forces a String into the pool for reference sharing
Constant folding Compile-time literal concatenation produces one object

Question 1 of 5

What does it mean for a Java String to be immutable?

Question 2 of 5

Given the code below, what is the output?

String x = "hello";
String y = "hello";
String z = new String("hello");

System.out.println(x == y);
System.out.println(x == z);

Question 3 of 5

Which class should you use to efficiently build a String inside a loop?

Question 4 of 5

What is the value of s after this code executes?

String s = "Java";
s.concat(" Rocks");
s.toUpperCase();
System.out.println(s);

Question 5 of 5

How many String objects are created by this single statement?

String s = "X" + "Y" + "Z";