StringBuffer is a mutable sequence of characters in Java. Unlike String, it allows modification of text without creating new objects, making it suitable for frequent string manipulations.
StringBuilder due to synchronizationThe StringBuffer class belongs to java.lang package and provides methods like append(), insert(), delete(), and reverse().
// Creating and modifying a StringBuffer
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
sb.insert(5, ",");
System.out.println(sb);
}
}
Hello, World
The original string is modified directly using append() and insert() without creating new objects.
Simulate StringBuffer operations live:
StringBuffer when thread safety is requiredStringBuilder for single-threaded applicationsStringBuffer and reverse its contentStringBuilder