8.1 String Immutability
Unlike C where strings are mutable character arrays, Java String objects are immutable: once created on the heap, their character contents can never be altered during their lifetime.
Operations that appear to "modify" a string (like concatenation via + or .concat()) do not modify the original object. Instead, Java creates a brand-new String object on the heap with the combined text, leaving the original object unchanged:
String s = "Cat";
s = s + "erpillar";
💡 Placement & Interview Deep-Dive: Why is String Immutable in Java?
- String Constant Pool (SCP): Allows string literals to be cached and reused across the entire JVM. If strings were mutable, changing one variable's text would corrupt all other variables referencing that shared literal!
- Security: Strings are used for database connection URLs, file paths, and network sockets. Immutability ensures malicious code cannot alter sensitive strings after validation.
- Thread Safety: Because string content never changes,
Stringobjects can be shared across multiple concurrent threads without needing synchronization or locks. - HashCode Caching: A string's
hashCode()is computed once and cached inside a privatehashfield. This guarantees lightning-fast $O(1)$ lookups when strings serve as keys in aHashMap.
8.2 StringBuilder and StringBuffer
Because String is immutable, performing repeated string concatenation inside a loop allocates numerous throwaway intermediate objects, causing performance degradation and GC thrashing. Java provides two mutable character buffer classes:
StringBuilder(Java 5+): Highly efficient mutable sequence of characters. Its methods are not synchronized, making it the fastest and recommended choice for single-threaded string manipulation.StringBuffer(Java 1.0): Similar to StringBuilder, but all public methods are synchronized (thread-safe), introducing locking overhead. Use only when multiple threads must modify the same buffer concurrently.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i).append(",");
}
System.out.println(sb.toString()); // Output: 0,1,2,3,4,
8.3 Common String Methods
The java.lang.String class provides an extensive library of text manipulation methods:
| Method | Return Type | Description | Example |
|---|---|---|---|
length() |
int |
Returns number of characters | "Java".length() → 4 |
charAt(int i) |
char |
Character at zero-based index i |
"Java".charAt(1) → 'a' |
substring(int a, int b) |
String |
Extracts substring from index a up to (not including) b |
"ReadyToGo".substring(5, 7) → "To" |
equals(Object o) |
boolean |
Compares character contents for exact equality | s1.equals(s2) |
split(String regex) |
String[] |
Splits string into array based on regular expression pattern | "a,b,c".split(",") |
DSA String Algorithms: Two-Pointer Palindrome
Checking whether a Java String is a palindrome is optimal using two inward-moving indices:
public static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++;
j--;
}
return true;
}