String Immutability Basics
What is String Immutability?
In Java, strings are immutable, which means once a String object is created, its content cannot be changed. When you perform operations that seem to modify a string, you're actually creating a new String object.
public class StringImmutabilityDemo {
public static void main(String[] args) {
String original = "Hello";
String modified = original.concat(" World");
System.out.println(original); // Prints: Hello
System.out.println(modified); // Prints: Hello World
}
}
Key Characteristics of String Immutability
Characteristic |
Description |
Unchangeable |
String contents cannot be modified after creation |
Memory Efficiency |
Allows string pooling and reuse |
Thread Safety |
Inherently safe in multi-threaded environments |
Memory Representation
graph TD
A[String Creation] --> B[Stored in String Pool]
B --> C{Reuse Existing String?}
C -->|Yes| D[Reference Existing String]
C -->|No| E[Create New String Object]
Why Immutability Matters
Immutability provides several benefits:
- Prevents unintended modifications
- Enables caching and reuse
- Supports thread-safe operations
- Simplifies complex string manipulations
Example of String Immutability
public class ImmutabilityExample {
public static void demonstrateImmutability() {
String original = "LabEx Tutorial";
String modified = original.toUpperCase();
// Original string remains unchanged
System.out.println(original); // Prints: LabEx Tutorial
System.out.println(modified); // Prints: LABEX TUTORIAL
}
}
While immutability provides safety, frequent string modifications can impact performance. For mutable string operations, consider using:
- StringBuilder
- StringBuffer (for thread-safe scenarios)