String represents fixed-length, immutable character sequences.
StringBuffer represents growable and writeable character sequences.
StringBuffer will automatically grow to make room for such additions.
Java manipulate StringBuffers behind the scenes when you are using the overloaded + operator.
Constructors:
StringBuffer()
Creates a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)
Creates a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
Creates a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
Creates a string buffer initialized to the contents of the specified string.
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer(20);
System.out.println(sb.capacity());
}
}
The output:
20
Using new StringBuffer(String str)
public class Main {
public static void main(String[] arg) {
StringBuffer aString = new StringBuffer("ABCDE");
String phrase = "abced";
StringBuffer buffer = new StringBuffer(phrase);
System.out.println(aString);
System.out.println(buffer);
}
}