› Module 8: Strings › 8.1 String Immutability
M O D U L E

Module 8: Strings

String immutability and memory mechanics, the String Constant Pool, StringBuilder vs StringBuffer, and essential methods.

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";
"Cat" object (unchanged, unreferenced) s = s + "erpillar" new "Caterpillar" object (s now points here)
Figure 8.1 — String concatenation never modifies the original object.

💡 Placement & Interview Deep-Dive: Why is String Immutable in Java?

  1. 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!
  2. Security: Strings are used for database connection URLs, file paths, and network sockets. Immutability ensures malicious code cannot alter sensitive strings after validation.
  3. Thread Safety: Because string content never changes, String objects can be shared across multiple concurrent threads without needing synchronization or locks.
  4. HashCode Caching: A string's hashCode() is computed once and cached inside a private hash field. This guarantees lightning-fast $O(1)$ lookups when strings serve as keys in a HashMap.

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;
}
i (charAt) j (charAt) m a d a m s.charAt(i) compares against s.charAt(j) without creating reverse string objects
Figure 8.3 — Two-pointer palindrome verification in Java with O(1) memory overhead.
MODULE COMPREHENSIVE QUIZ

Module 8 Final Quiz

Test your understanding across all 3 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 8 Final Quiz →
Yukti Mascot