← Back to Chapters

Java String Immutability

? Java String Immutability

? Quick Overview

In Java, String objects are immutable, meaning once a String is created, its value cannot be changed. Any operation that appears to modify a String actually creates a new String object.

? Key Concepts

  • String objects cannot be modified after creation
  • Changes result in new objects in memory
  • Improves security, caching, and thread-safety
  • Stored in the String Constant Pool (SCP)

? Syntax / Theory

When you perform operations like concatenation, replacement, or case conversion, Java does not alter the original String. Instead, it creates a new one.

? View Code Example
// Demonstrating immutability of String
String s1 = "Java";
s1.concat(" Programming");
System.out.println(s1);

?️ Live Output / Explanation

Output

Java

The original String s1 remains unchanged because concat() creates a new String but does not assign it back to s1.

? Code Example with New Object

? View Code Example
// Assigning the new String reference
String s1 = "Java";
s1 = s1.concat(" Programming");
System.out.println(s1);

? Explanation

Here, the new String created by concat() is assigned back to s1, so the updated value is displayed.

? Interactive Memory Lab

Enter a string and click an operation. Notice how the Original object remains in memory, and a completely New Object is created with a different memory address.

 

✅ Tips & Best Practices

  • Use StringBuilder or StringBuffer for frequent modifications
  • Immutability improves security and thread-safety
  • Helps Java optimize memory using String Pool

? Try It Yourself

  • Create two Strings with same value and compare memory references
  • Test immutability using toUpperCase()
  • Replace characters and observe object creation