DevNotes
Support
Core Java · Chapter 06

String, StringBuilder & StringBuffer

Immutability, the String Constant Pool, mutable builders, capacity growth and choosing the right class.

◷ 6 min read§ 20 sections? 10 interview questions{ } 18 code examples

#Introduction

One of the most important Java interview topics is the difference between:

  • String
  • StringBuilder
  • StringBuffer

Every Java developer must know:

  • Why String is immutable
  • Why StringBuilder is faster
  • Why StringBuffer is thread-safe
  • When to use each one

This topic is asked in almost every Java interview for 2–10 years of experience.

#What is a String?

A String is a sequence of characters.

Java
String name = "Java";

Internally: J A V A

But unlike arrays, a String object cannot be modified after it is created. This property is called Immutability.

#Creating Strings

There are two ways.

Method 1 — Using a String Literal

Java
String s1 = "Java";

Stored in the String Constant Pool (SCP).

Method 2 — Using new

Java
String s2 = new String("Java");

Stored in Heap Memory.

#String Constant Pool (SCP)

Java maintains a special memory area called the String Constant Pool. Purpose: avoid duplicate String objects.

Java
String s1 = "Java";
String s2 = "Java";
s1s2
String Pool"Java"
Only one object exists, so memory is saved

Using new

Java
String s1 = new String("Java");
String s2 = new String("Java");
s1
Heap · Object A
s2
Heap · Object B
Now two objects exist

#Why is String Immutable?

Java
String s = "Java";
s.concat("8");
Output
Java

The original object is unchanged. Correct:

Java
s = s.concat("8");
Output
Java8

A new String object is created.

Internal Working

Java
String s = "Java";
s = s.concat("17");
Befores → "Java"
After concats → "Java17""Java" still exists
The old object remains unchanged until garbage collected

Advantages of Immutability

  • Thread-safe
  • Secure
  • Enables String Pool
  • Safe as HashMap keys
  • Easy caching
  • Better performance in many scenarios

#Common String Methods

Java
String s = "Java Programming";
OperationCodeOutput
Lengths.length()16
Characters.charAt(2)v
Substrings.substring(5)Programming
Containss.contains("Prog")true
Replaces.replace("Java", "Python")Python Programming
Uppercases.toUpperCase()JAVA PROGRAMMING
Lowercases.toLowerCase()java programming
Trim" Java ".trim()Java
Splits.split(" ")["Java", "Programming"]

#StringBuilder

StringBuilder is a mutable sequence of characters.

Java
StringBuilder sb = new StringBuilder("Java");
sb.append("17");
Output
Java17

No new object is created. The existing object is modified.

Internal Working

StringBuilder"Java"
"Java17"
"Java17 Spring"
"Java17 Spring Boot"
Same object throughout

#StringBuffer

StringBuffer is also mutable.

Java
StringBuffer sb = new StringBuffer("Java");
sb.append("17");
Output
Java17

Works almost like StringBuilder.

#Difference Between StringBuilder and StringBuffer

The major difference is thread safety.

  • StringBuffer — uses synchronized methods. Safe for multiple threads.
  • StringBuilder — does not use synchronization. Much faster.

#Performance Comparison

Java
String s = "";

for (int i = 0; i < 10000; i++) {
    s = s + i;
}

Every iteration creates a new String object. Very slow.

Using StringBuilder:

Java
StringBuilder sb = new StringBuilder();

for (int i = 0; i < 10000; i++) {
    sb.append(i);
}

Only one object. Much faster.

#String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBuffer
MutableNoYesYes
Thread SafeYes (immutable)NoYes
PerformanceSlow for repeated modificationFastestSlightly slower
SynchronizationNot requiredNoYes
MemoryCreates new object on modificationSame objectSame object

#Capacity

Default capacity:

Java
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());
Output
16

With Initial String

Java
StringBuilder sb = new StringBuilder("Java");

Capacity = length + 16 = 4 + 16 = 20.

Capacity Expansion

When capacity is exceeded, Java expands using:

Text
newCapacity = (oldCapacity * 2) + 2
16
34
70
142
This minimizes reallocations and improves performance

#Common Methods

MethodCode
Appendsb.append("Java");
Insertsb.insert(4, "8");
Deletesb.delete(2, 5);
Reversesb.reverse();
Replacesb.replace(0, 4, "Python");
Lengthsb.length();
Capacitysb.capacity();

#String Pool Examples

Java
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);
Output
true
Java
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);
Output
false

intern() Method

Java
String s1 = new String("Java");
String s2 = s1.intern();
System.out.println(s2 == "Java");
Output
true

intern() returns the pooled String if it already exists; otherwise it adds the string to the pool.

#Real Project Usage

String

  • Configuration values
  • JSON keys
  • API URLs
  • Database column names

StringBuilder

  • Building SQL queries
  • Generating reports
  • Creating JSON or XML
  • Constructing log messages

StringBuffer

  • Legacy multi-threaded code
  • Older APIs requiring synchronized mutable strings

#Interview Questions

Q1Why is String immutable?

For security, thread safety, caching, and efficient use of the String Constant Pool.

Q2Where are String literals stored?

In the String Constant Pool.

Q3Where are Strings created using new stored?

In Heap Memory.

Q4Which is faster?

StringBuilder, because it is not synchronized.

Q5Which is thread-safe?

StringBuffer.

Q6Can StringBuilder be shared safely across multiple threads?

No. Use external synchronization or StringBuffer if required.

Q7Why does String concatenation inside loops perform poorly?

Because each concatenation creates a new immutable String object.

Q8What is the default capacity of StringBuilder?

16 characters.

Q9What does intern() do?

It returns the canonical representation of a string from the String Constant Pool.

Q10Should we always use StringBuilder instead of String?

No. Use String for immutable text and ordinary values. Use StringBuilder only when frequent modifications are required.

#Common Mistakes

  • Using String concatenation inside loops.
  • Using == for String content comparison.
  • Using StringBuffer unnecessarily in single-threaded code.
  • Assuming concat() modifies the original String.

#Best Practices

  • Use String for constants and immutable values.
  • Use StringBuilder for repeated string modifications.
  • Use StringBuffer only when synchronized mutable strings are genuinely needed.
  • Use equals() instead of == for comparing String contents.
  • Prefer StringBuilder in loops and high-performance code.

#Quick Revision

String
Immutable
Thread Safe
String Pool
StringBuilder
Mutable
Fast
Not Thread Safe
StringBuffer
Mutable
Thread Safe
Synchronized

#Chapter Summary

After completing this chapter, you should be able to:

  • Explain why String is immutable.
  • Describe the String Constant Pool and how it saves memory.
  • Understand the differences between String, StringBuilder, and StringBuffer.
  • Explain capacity and internal expansion of StringBuilder.
  • Choose the right class based on performance and thread-safety requirements.
  • Confidently answer interview questions related to String handling in Java.