Why String is Immutable in Java: Explanation and Examples
In Java,
String objects are immutable to improve security, performance, and thread safety. Once created, a String cannot be changed, which allows safe sharing and efficient memory use through string pooling.Syntax
The String class in Java is declared as final, which means it cannot be subclassed or changed after creation. You create strings using double quotes or the new String() constructor.
String s = "hello";creates a string literal.String s2 = new String("hello");creates a new string object.
Because strings are immutable, any operation that seems to modify a string actually creates a new string object.
java
String s = "hello"; String s2 = new String("hello"); String s3 = s.concat(" world");
Example
This example shows that modifying a string creates a new object, leaving the original unchanged.
java
public class StringImmutableExample { public static void main(String[] args) { String original = "hello"; String modified = original.concat(" world"); System.out.println("Original string: " + original); System.out.println("Modified string: " + modified); } }
Output
Original string: hello
Modified string: hello world
Common Pitfalls
Many beginners expect strings to change when using methods like concat() or replace(). However, these methods return new strings and do not modify the original.
For example, doing str.concat("abc"); without assignment does nothing to str.
java
public class StringPitfall { public static void main(String[] args) { String str = "hello"; str.concat(" world"); // This does NOT change str System.out.println(str); // Prints "hello" str = str.concat(" world"); // Correct way to update System.out.println(str); // Prints "hello world" } }
Output
hello
hello world
Quick Reference
- Immutable: String objects cannot be changed after creation.
- Security: Prevents unauthorized changes to string data.
- Performance: Enables string pooling and reuse.
- Thread Safety: Safe to share strings across threads without synchronization.
Key Takeaways
Strings in Java are immutable to ensure security, performance, and thread safety.
Any modification to a string creates a new string object; the original remains unchanged.
Always assign the result of string operations to a variable to capture changes.
Immutability allows Java to use string pooling for memory efficiency.
Immutable strings are safe to share between multiple threads without extra synchronization.