Fundamentals 16 min read

Understanding Java String, StringBuilder, and StringBuffer: Differences, Performance, and Interview Questions

This article explains the internal implementation of Java's String class, compares it with StringBuilder and StringBuffer, demonstrates performance differences through benchmark code, and provides common interview questions with detailed answers, helping developers choose the appropriate class for various scenarios.

Java Captain
Java Captain
Java Captain
Understanding Java String, StringBuilder, and StringBuffer: Differences, Performance, and Interview Questions

Java's String class is one of the most frequently used classes and a common interview topic. Its source code resides in jdk1.6.0_14/src/java/lang/String.java and shows that the class is declared final , meaning it cannot be subclassed. The class stores characters in a private final char[] value array together with offset , count , and a cached hash field.

Key methods such as substring , concat , and replace always create a new String object instead of modifying the original, confirming the immutability of String . The rule "any change to a String object generates a new object" is emphasized.

When comparing literals and objects created with new String() , the JVM uses the runtime constant pool. Literals like String s1 = "hello world" and String s3 = "hello world" refer to the same object, while new String("hello world") always creates a distinct object on the heap.

The article then contrasts String , StringBuilder , and StringBuffer . StringBuilder is preferred for single‑threaded concatenation, while StringBuffer adds the synchronized keyword for thread safety. Sample code demonstrates that using string += "hello" inside a loop causes the JVM to create a new StringBuilder for each iteration, leading to many temporary objects.

public class Main {
    public static void main(String[] args) {
        String string = "";
        for (int i = 0; i < 10000; i++) {
            string += "hello"; // compiled to new StringBuilder each loop
        }
    }
}

A more efficient version creates a single StringBuilder before the loop and reuses it:

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            sb.append("hello");
        }
    }
}

Performance tests (executed on Windows 7, Eclipse, JDK 6) show the typical ranking: StringBuilder > StringBuffer > String . However, simple compile‑time concatenations like "I" + "love" + "java" are optimized to a single constant and can be faster than using a builder.

Based on these observations, the article recommends using plain String for infrequent or small concatenations, StringBuilder for intensive single‑threaded modifications, and StringBuffer when thread safety is required.

The final section lists common interview questions about String and StringBuffer , such as the results of comparing literals, the effect of final variables, the behavior of intern() , and how many objects are created by new String("abc") . Each question is answered with an explanation of the underlying JVM mechanisms.

Overall, the article provides a comprehensive guide to the internal workings, performance characteristics, and practical usage of Java's string handling classes.

JavaPerformanceinterviewString()memoryStringBuilderStringBuffer
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.