Back to course

Manipulating Text: The String Class vs. StringBuilder/StringBuffer

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 30: Manipulating Text: String Class vs. StringBuilder/StringBuffer

Text handling is fundamental in programming, and Java provides three primary classes for this.

1. The String Class (Immutable)

Strings in Java are immutable, meaning once a String object is created, its value cannot be changed. Any operation that appears to modify a string (like concatenation) actually creates a brand new string object in memory.

java String s = "Java"; s = s + " Course"; // A new String object is created and 's' points to it.

// Common String Methods: String name = " Alice "; name = name.trim(); // "Alice" int index = name.indexOf('i'); // 2 boolean check = name.startsWith("Al"); // true

When to use String: For simple, constant text data or when string values do not change frequently.

2. StringBuilder (Mutable and Non-Synchronized)

StringBuilder objects are mutable, meaning they can be modified without creating a new object every time. This makes them highly efficient for operations that involve frequent modification (appending, inserting, deleting).

java StringBuilder sb = new StringBuilder("Start"); sb.append("ing"); // sb still points to the same object in memory sb.insert(0, "Re");

System.out.println(sb.toString()); // Output: Restarting

When to use StringBuilder: When performing heavy string manipulation within a single thread (most common scenario).

3. StringBuffer (Mutable and Synchronized)

StringBuffer is functionally identical to StringBuilder, but its methods are synchronized (thread-safe). Synchronization adds overhead.

When to use StringBuffer: Only when working in a multi-threaded environment where multiple threads might access and modify the same sequence simultaneously (less common for beginners).

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
PerformanceSlow (on modification)FastSlower (due to synchronization)
Thread SafeYes (Immutable by nature)NoYes