Introduction
In Java, strings are used everywhere β for messages, input handling, formatting, file processing, and much more β
But there is one important thing many beginners donβt realize:
π String objects in Java are immutable.
This means once a String object is created, it cannot be changed.
So what happens when we keep modifying a string inside a loop?
It creates multiple new objects in memory β
This reduces performance and wastes memory.
To solve this problem, Java provides:
π― StringBuilder
π§ What is StringBuilder?
StringBuilder is a class in the java.lang package used to create mutable strings.
Mutable means:
The content can be modified without creating a new object.
π₯ Why Do We Need StringBuilder?
Letβs first see the problem with String.
β Problem with String (Immutable)
public class StringProblem {
public static void main(String[] args) {
String str = "Java";
str = str + " Programming";
str = str + " Language";
System.out.println(str);
}
}
π§ What Happens Internally?
Each concatenation:
- Creates a new String object
- Copies old content
- Adds new content
- Discards old object
This is inefficient in loops.
β Solution: StringBuilder
π’ Example 1: Basic StringBuilder
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
sb.append(" Language");
System.out.println(sb);
}
}
π§ Step-by-Step Explanation
1οΈβ£ StringBuilder sb = new StringBuilder("Java");
Creates a mutable string object.
2οΈβ£ append() modifies the same object.
3οΈβ£ No new object is created during modification.
4οΈβ£ Efficient memory usage.
π String vs StringBuilder
| Feature | String | StringBuilder |
|---|---|---|
| Mutable | β No | β Yes |
| Performance | Slower (in loops) | Faster |
| Thread-safe | Yes | No |
| Memory efficient | Less | More |
π§ Important Methods of StringBuilder
πΉ 1οΈβ£ append()
Adds text at the end.
sb.append("Hello");
πΉ 2οΈβ£ insert()
Inserts text at specific index.
sb.insert(4, "World ");
πΉ 3οΈβ£ delete()
Removes characters.
sb.delete(0, 4);
πΉ 4οΈβ£ reverse()
Reverses the string.
sb.reverse();
πΉ 5οΈβ£ replace()
Replaces part of string.
sb.replace(0, 4, "Hi");
π’ Example 2: Using Multiple Methods
public class StringBuilderMethods {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Language");
sb.insert(5, "Programming ");
sb.replace(0, 4, "Core");
sb.delete(5, 16);
System.out.println(sb);
}
}
π§ Explanation
- append() β adds text
- insert() β inserts at position
- replace() β replaces characters
- delete() β removes characters
All operations modify the same object.
π Converting StringBuilder to String
Sometimes we need a String object.
String str = sb.toString();
π’ Example 3
public class ConvertDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
String str = sb.toString();
System.out.println(str);
}
}
π Performance Advantage
Consider concatenation in a loop:
β Using String
String str = "";
for(int i = 0; i < 1000; i++) {
str += i;
}
Creates 1000+ objects β
β Using StringBuilder
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 1000; i++) {
sb.append(i);
}
Uses single object β
Much faster and memory-efficient.
π§ Memory Concept
- String β stored in String Pool
- StringBuilder β stored in Heap
- Modifications do not create new object
β Common Confusions
β Is StringBuilder thread-safe?
No β
If multiple threads modify it simultaneously, it may cause issues.
For thread safety β use StringBuffer.
β Is StringBuilder better than String?
Depends.
β Use String when:
- Data does not change
β Use StringBuilder when:
- Frequent modification required
β Common Mistakes
β Forgetting to use toString()
String str = sb; // β Error
Correct:
String str = sb.toString();
β Using String instead of StringBuilder in loops
Leads to poor performance.
β Confusing StringBuffer and StringBuilder
- StringBuffer β Thread-safe
- StringBuilder β Faster but not thread-safe
π§ͺ Tricky Example
public class TrickyExample {
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder("Java");
StringBuilder sb2 = sb1;
sb1.append(" Programming");
System.out.println(sb2);
}
}
π§ Why Does This Print Modified Value?
Because both sb1 and sb2 refer to the same object.
StringBuilder is mutable.
π― When Should You Use StringBuilder?
β Inside loops
β For dynamic string building
β For text processing
β For performance optimization
π Interview/Viva Important Points
- String is immutable
- StringBuilder is mutable
- StringBuilder introduced in Java 5
- Faster than StringBuffer
- Not thread-safe
- append() does not create new object
β Conclusion
StringBuilder is a powerful and efficient way to handle dynamic string manipulation in Java π
It solves the performance problems caused by String immutability and provides multiple useful methods for string modification.
By understanding:
- Why String is immutable
- How StringBuilder works
- When to use it
- Its performance benefits
You significantly improve your Java programming efficiency πͺ
Mastering StringBuilder is essential for writing optimized and professional Java applications.