Launch your tech mastery with us—your coding journey starts now!
Course Content
Data Structure

Since standard Strings are immutable, creating a string inside a loop (like s = s + “a”) is a performance disaster. It creates N new objects for N iterations.

To solve this, Java provides StringBuilder and StringBuffer. They are mutable (modifiable) sequences of characters.

Feature String StringBuilder StringBuffer
Modifiable? No (Immutable) Yes (Mutable) Yes (Mutable)
Performance Slow for concatenation Fastest Moderate
Thread Safe? Yes No Yes (Synchronized)
Use Case Storing constants, IDs Building strings in loops Multi-threaded apps

Code Example: Efficient String Manipulation

public class StringBuilderDemo {
    public static void main(String[] args) {
        // Inefficient way (Don't do this in large loops!)
        String slow = "";
        for(int i=0; i<5; i++) {
            slow = slow + i; // Creates 5 new objects
        }

        // Efficient way (Use StringBuilder)
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<5; i++) {
            sb.append(i); // Modifies the existing object
        }
        
        // Convert back to String when done
        String fast = sb.toString(); 
        System.out.println(fast); // Output: 01234
        
        // Reverse a String (Easy with StringBuilder)
        System.out.println("Reversed: " + sb.reverse().toString()); // Output: 43210
    }
}