String, StringBuilder & StringBuffer
Immutability, the String Constant Pool, mutable builders, capacity growth and choosing the right class.
#Introduction
One of the most important Java interview topics is the difference between:
StringStringBuilderStringBuffer
Every Java developer must know:
- Why
Stringis immutable - Why
StringBuilderis faster - Why
StringBufferis 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.
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
String s1 = "Java";Stored in the String Constant Pool (SCP).
Method 2 — Using new
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.
String s1 = "Java";
String s2 = "Java";Using new
String s1 = new String("Java");
String s2 = new String("Java");#Why is String Immutable?
String s = "Java";
s.concat("8");JavaThe original object is unchanged. Correct:
s = s.concat("8");Java8A new String object is created.
Internal Working
String s = "Java";
s = s.concat("17");Advantages of Immutability
- Thread-safe
- Secure
- Enables String Pool
- Safe as
HashMapkeys - Easy caching
- Better performance in many scenarios
#Common String Methods
String s = "Java Programming";| Operation | Code | Output |
|---|---|---|
| Length | s.length() | 16 |
| Character | s.charAt(2) | v |
| Substring | s.substring(5) | Programming |
| Contains | s.contains("Prog") | true |
| Replace | s.replace("Java", "Python") | Python Programming |
| Uppercase | s.toUpperCase() | JAVA PROGRAMMING |
| Lowercase | s.toLowerCase() | java programming |
| Trim | " Java ".trim() | Java |
| Split | s.split(" ") | ["Java", "Programming"] |
#StringBuilder
StringBuilder is a mutable sequence of characters.
StringBuilder sb = new StringBuilder("Java");
sb.append("17");Java17No new object is created. The existing object is modified.
Internal Working
#StringBuffer
StringBuffer is also mutable.
StringBuffer sb = new StringBuffer("Java");
sb.append("17");Java17Works almost like StringBuilder.
#Difference Between StringBuilder and StringBuffer
The major difference is thread safety.
StringBuffer— usessynchronizedmethods. Safe for multiple threads.StringBuilder— does not use synchronization. Much faster.
#Performance Comparison
String s = "";
for (int i = 0; i < 10000; i++) {
s = s + i;
}Every iteration creates a new String object. Very slow.
Using StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}Only one object. Much faster.
#String vs StringBuilder vs StringBuffer
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread Safe | Yes (immutable) | No | Yes |
| Performance | Slow for repeated modification | Fastest | Slightly slower |
| Synchronization | Not required | No | Yes |
| Memory | Creates new object on modification | Same object | Same object |
#Capacity
Default capacity:
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());16With Initial String
StringBuilder sb = new StringBuilder("Java");Capacity = length + 16 = 4 + 16 = 20.
Capacity Expansion
When capacity is exceeded, Java expands using:
newCapacity = (oldCapacity * 2) + 2#Common Methods
| Method | Code |
|---|---|
| Append | sb.append("Java"); |
| Insert | sb.insert(4, "8"); |
| Delete | sb.delete(2, 5); |
| Reverse | sb.reverse(); |
| Replace | sb.replace(0, 4, "Python"); |
| Length | sb.length(); |
| Capacity | sb.capacity(); |
#String Pool Examples
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);trueString s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);falseintern() Method
String s1 = new String("Java");
String s2 = s1.intern();
System.out.println(s2 == "Java");trueintern() 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.
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
Stringconcatenation inside loops. - Using
==forStringcontent comparison. - Using
StringBufferunnecessarily in single-threaded code. - Assuming
concat()modifies the originalString.
#Best Practices
- Use
Stringfor constants and immutable values. - Use
StringBuilderfor repeated string modifications. - Use
StringBufferonly when synchronized mutable strings are genuinely needed. - Use
equals()instead of==for comparingStringcontents. - Prefer
StringBuilderin loops and high-performance code.
#Quick Revision
#Chapter Summary
After completing this chapter, you should be able to:
- Explain why
Stringis immutable. - Describe the String Constant Pool and how it saves memory.
- Understand the differences between
String,StringBuilder, andStringBuffer. - Explain capacity and internal expansion of
StringBuilder. - Choose the right class based on performance and thread-safety requirements.
- Confidently answer interview questions related to
Stringhandling in Java.