Java StringBuilder & StringBuffer
In this page:
Introduction to StringBuilder
StringBuilder builds a mutable sequence of characters that can be changed in place, which makes it dramatically faster than repeated String concatenation inside a loop — each += on a String silently creates a whole new String object, while StringBuilder.append() just extends an internal buffer.
Example: Introduction to StringBuilder
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
System.out.println(sb);
}
}
Login to try C/C++/Java/PHP code in the editor
Inserting and Deleting
Because StringBuilder is mutable, you can insert characters at any position with insert(index, value) or remove a range with delete(start, end) without creating a new object each time, unlike the equivalent operations on an immutable String.
Example: Inserting and Deleting
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, ",");
System.out.println(sb);
sb.delete(0, 6);
System.out.println(sb);
}
}
Login to try C/C++/Java/PHP code in the editor
Reversing with StringBuilder
reverse() flips the entire character sequence in place, which is a frequent building block in coding interview problems like palindrome checks or digit-reversal puzzles — it's far simpler than manually swapping characters from both ends.
Example: Reversing with StringBuilder
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);
}
}
Login to try C/C++/Java/PHP code in the editor
Checking Capacity and Length
length() reports how many characters are currently stored, while capacity() reports how much internal buffer space is allocated before the builder needs to grow and reallocate — capacity is always greater than or equal to length, and you rarely need to think about it unless you're optimizing for performance.
Example: Checking Capacity and Length
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
System.out.println(sb.length());
System.out.println(sb.capacity());
}
}
Login to try C/C++/Java/PHP code in the editor
Thread Safe StringBuffer
StringBuffer has an identical API to StringBuilder but synchronizes its methods, making it safe to share across multiple threads at the cost of extra locking overhead. Use StringBuilder by default for single-threaded code, and reach for StringBuffer only when you actually need that thread safety.
Example: Thread Safe StringBuffer
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" World");
System.out.println(sb);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: