String is immutable in Java, which means that once a String object is created, its value cannot be changed. Any operation that appears to modify a String actually creates a new String object. This design improves security, performance, thread safety, and memory efficiency.
Key Points
Immutability means the content of a String cannot be modified after creation.
String objects are safely shared through the String Pool because their values cannot change.
Immutable strings are inherently thread-safe and can be accessed by multiple threads without synchronization.
Immutability enhances security by preventing sensitive data such as file paths, database URLs, and network connections from being altered unexpectedly.
Hash codes can be cached because the String value never changes, improving the performance of collections like HashMap.
Example
When a String is modified using concatenation, Java creates a new object instead of changing the existing one.
public class Demo {
public static void main(String[] args) {
String str = "Java";
str.concat(" Programming");
System.out.println(str);
str = str.concat(" Programming");
System.out.println(str);
}
}
Output
Java
Java Programming
Benefits of String Immutability
Improved security
Better thread safety
Efficient String Pool implementation
Reliable hash code caching
Simplified memory management
Common Mistakes
Thinking String methods like toUpperCase() change the original string. They return a new String.
Building strings with + inside loops, which creates many temporary objects. Use StringBuilder.
Follow-up Questions
Can you break String immutability? Only with reflection on internal fields, which is unsafe and blocked by module rules in recent Java versions.
Why does immutability help HashMap keys? The hash code cannot change after the key is stored, so the entry is always found.
Interview Tip
A concise interview answer is
String is immutable in Java, meaning its value cannot be changed after creation. This design improves security, enables String Pool optimization, provides thread safety, and enhances performance through hash code caching and efficient memory management.