Java
Module 6: Java Strings & StringBuilderBeginner22 min read

StringBuilder, StringBuffer & Immutable Classes

Compare String, StringBuilder, and StringBuffer for performance and thread safety, and learn how to design your own immutable Java class.

Key Takeaways & Core Concepts
  • time and flooding Garbage Collection. Use StringBuilder for mutable string assembly in O(n) time.
  • | Immutable | Mutable | Mutable |
  • | Yes (immutable) | No (single-thread) | Yes (synchronized methods) |
  • | O(n^2) in loops | Fastest (O(n)) | Slower due to lock overhead |

String vs StringBuilder vs StringBuffer

Because String is immutable, concatenating strings inside a for loop (res += item;) creates a brand-new String object on every iteration—degrading performance to O(n^2) time and flooding Garbage Collection. Use StringBuilder for mutable string assembly in O(n) time.

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-SafeYes (immutable)No (single-thread)Yes (synchronized methods)
PerformanceO(n^2) in loopsFastest (O(n))Slower due to lock overhead
StringBuilder & Custom Immutable Class
1final class ImmutableTag {
2 private final String name;
3 ImmutableTag(String name) { this.name = name; }
4 public String getName() { return name; }
5}
6
7public class Main {
8 public static void main(String[] args) {
9 StringBuilder sb = new StringBuilder();
10 for (int i = 1; i <= 3; i++) sb.append("Item").append(i).append(" ");
11 System.out.println(sb.toString().trim());
12 System.out.println("Reversed: " + new StringBuilder("level").reverse());
13 System.out.println("Tag: " + new ImmutableTag("Java21").getName());
14 }
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: `StringBuilder` resizes its internal character array amortized O(1) per append.

Designing Your Own Immutable Class

  1. 1
    Mark the class final so it cannot be subclassed.
  2. 2
    Make all fields private final.
  3. 3
    Do not provide any setter methods.
  4. 4
    Perform defensive copies for any mutable fields (like Date or List) in the constructor and getters.
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)