String
String Creation and Memory
String Initialization
In Java, String is a final class, meaning it cannot be extended. Strings are objects and can be created in two ways:
- String Literal (Recommended): Stored in the String Constant Pool, reuses references for identical strings.
String Immutability and Garbage Collection
Strings are immutable. Modifying a string creates a new object, leaving the original eligible for garbage collection if unreferenced.
Mutable Strings
Mutable Strings
- StringBuilder: Faster, not thread-safe.
- StringBuffer: Thread-safe, slower due to synchronization.
Use
StringBuilderfor performance in single-threaded scenarios andStringBufferfor thread-safe operations.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the original object
System.out.println(sb); // Outputs: Hello World
Use these classes in loops or for frequent string modifications to avoid creating multiple immutable objects.