Beginner's Guide to Java Strings, StringBuffer, and StringBuilder

Java provides multiple classes to handle text data: String
, StringBuffer
, and StringBuilder
. Each class serves a unique purpose and comes with its own characteristics, strengths, and drawbacks. This blog explores these classes in depth with examples, explanations, and best practices.
πΉ 1. Java String Class: Immutable Character Sequences
What is a String?
A String
in Java is an object that represents a sequence of characters. Unlike C/C++, where strings are arrays of characters, Java String
is a class from java.lang
package.
String message = "Hello, World!";
Why Strings Are Immutable
In Java, strings are immutable, meaning once a String
object is created, its content cannot be changed. Any operation that seems to modify a string will actually create a new string object.
Example:
String original = "Hello";
String modified = original.concat(" World");
System.out.println(original); // Output: Hello
System.out.println(modified); // Output: Hello World
Explanation:
original.concat(" World")
returns a new String object.The original
String
remains unchanged.
Advantages of Immutability
Thread Safety: Safe to use across threads without synchronization.
Security: Prevents changes to sensitive strings like file paths, passwords.
Hashing Optimization: Hash code is cached.
String Pooling: Optimizes memory.
Disadvantages
- Performance Hit when modifying strings repeatedly (especially in loops).
πΉ 2. String Pool: Memory Management in Action
String Literals and Pooling
When you create a string literal:
String a = "Test";
String b = "Test";
Only one object is created and both a
and b
point to the same memory location from the String pool.
Example:
String a = "Java";
String b = "Java";
System.out.println(a == b); // true (same memory reference)
Using new
keyword:
String c = new String("Java");
System.out.println(a == c); // false (different objects)
Pros:
Saves memory
Faster comparison using
==
Cons:
- Risk of confusion between
==
(reference) and.equals()
(value).
πΉ 3. Common String Methods
Method | Description | Example Output |
length() | Returns length of string | "Java".length() β 4 |
charAt(index) | Returns char at specified index | "Java".charAt(1) β 'a' |
substring(start) | Part from start index | "Java".substring(2) β "va" |
equals() | Compares values | "test".equals("test") β true |
replace(old, new) | Replaces substring | "abc".replace("a", "x") β xbc |
split(delimiter) | Splits string | "a,b".split(",") β [a, b] |
πΉ 4. StringBuffer: Mutable and Thread-Safe
What is StringBuffer?
StringBuffer
is a mutable sequence of characters. Unlike String
, it allows content to be changed without creating a new object. It is also synchronized, which means multiple threads can access it safely β one thread at a time.
Key Characteristics:
Mutable: Can change contents after creation.
Thread-safe: Uses synchronization, ensuring safe access in multi-threaded environments.
Less memory usage than creating multiple immutable
String
objects.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Hello World
Additional Methods:
sb.append("!"); // Hello World!
sb.insert(5, ","); // Hello, World!
sb.replace(6, 11, "Java"); // Hello, Java!
sb.delete(0, 6); // Java!
sb.reverse(); // !avaJ
Explanation of Methods:
append()
: Adds text to the end.insert()
: Inserts text at a specified position.replace(start, end, str)
: Replaces text between indexes.delete(start, end)
: Removes characters.reverse()
: Reverses the character sequence.
Internal Working:
Uses a character array internally.
Automatically resizes when more space is needed (similar to ArrayList).
Thread-safe because all methods are synchronized.
Pros:
Efficient for frequent string manipulations.
Safe for concurrent access.
Flexible methods (insert, delete, etc.).
Cons:
Slower in single-threaded environments due to the overhead of synchronization.
Bulkier syntax compared to
String
.
When to Use:
Use StringBuffer
when:
You need to modify string content frequently.
You are working in multi-threaded environments.
πΉ 5. StringBuilder: Mutable and Fast (Not Thread-Safe)
What is StringBuilder?
StringBuilder
is like StringBuffer
but non-synchronized, making it faster in single-threaded environments.
Example:
StringBuilder sb = new StringBuilder("Hi");
sb.append(" there");
System.out.println(sb); // Hi there
Pros:
Mutable and faster than StringBuffer
Ideal for string concatenation in loops
Cons:
- Not thread-safe
πΉ 6. Performance Comparison
Concatenation in a Loop:
int n = 10000;
long t1 = System.nanoTime();
String s = "";
for(int i = 0; i < n; i++) s += i;
System.out.println("String: " + (System.nanoTime() - t1));
long t2 = System.nanoTime();
StringBuffer sbf = new StringBuffer();
for(int i = 0; i < n; i++) sbf.append(i);
System.out.println("StringBuffer: " + (System.nanoTime() - t2));
long t3 = System.nanoTime();
StringBuilder sbd = new StringBuilder();
for(int i = 0; i < n; i++) sbd.append(i);
System.out.println("StringBuilder: " + (System.nanoTime() - t3));
Expected Output:
String
: SlowestStringBuffer
: FasterStringBuilder
: Fastest
π 7. String vs StringBuffer vs StringBuilder: Summary Table
Feature | String | StringBuffer | StringBuilder |
Mutable | β No | β Yes | β Yes |
Thread-Safe | β Yes | β Yes | β No |
Performance | Slow | Medium | β Fast |
Use in Loops | β Avoid | Possible | β Recommended |
Memory Usage | High | Medium | β Low |
πΉ 8. When to Use What?
Use Case | Recommended Class |
Constant, fixed text (e.g., config key) | String |
Building strings in loops (single-threaded) | StringBuilder |
Building strings in multi-threaded env | StringBuffer |
String manipulation (insert, delete, etc.) | StringBuilder /Buffer |
π Quiz Section
- Whatβs the output?
String s = "Java";
s.concat("Script");
System.out.println(s);
Answer: Java
(Strings are immutable)
- Which one is thread-safe?
a. String
b. StringBuffer
c. StringBuilder
d. Both a and b Answer: d
Which is fastest for loops? Answer: StringBuilder
Can you modify a
String
object in Java?Answer: No, it's immutable. Methods return new objects.
When is
StringBuffer
preferred overStringBuilder
?
Answer: In multi-threaded environments.Can two
String
objects have the same value but different references?
Answer: Yes, if created usingnew String()
.
This blog aims to make you confident in handling Java strings and knowing when to choose which class. Understanding their internal behavior can save you from performance pitfalls and help you write efficient, robust code.
Subscribe to my newsletter
Read articles from Nagendra simhadri directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nagendra simhadri
Nagendra simhadri
A seasoned professional in financial technology and embedded software, recognized for driving revenue growth and customer satisfaction through innovative projects.