STRINGBUFFER
AND
STRINGBUILDER
What is the difference between String and StringBuffer classes?
▪ String class objects are immutable hence their contents can’t be
modified.
▪ StringBuffer class objects are mutable, so they can be modified.
Classes like Character, Byte, Integer, Float, Double, Long are called
wrapper classes are created as immutable.
Creating StringBuffer Objects:-
We can create StringBuffer objects by using new operator.
i.e
StringBuffer sb=new StringBuffer(“hello”);
Note:-
When we will simple write
StringBuffer sb=new StringBuffer();
Here sb object will be created with a default capacity of 16
characters.
Then we can use sb to append data.
i.e
sb.append(“hello”);
Methods of StringBuffer Class:-
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();
System.out.println("Initial Capacity : " +sb.capacity());
System.out.println("String appended : " +sb.append ("Dogs bark at
night"));
System.out.println("String replaced: " +sb.replace (10,12,"during"));
System.out.println("String reversed : " +sb.reverse());
System.out.println("Current Capacity : " +sb.capacity());
System.out.println("character at position 3 is: " + sb.charAt(3));
sb.setCharAt(3,‘a’);
System.out.println("sb after setting \"a\" at 3: " +sb);
}}
Output
C:\javabook>java StringBufferDemo
Initial Capacity : 16
String appended : Dogs bark at night
String replaced : Dogs bark during night
String reversed : thgin gnirud krab sgoD
Current Capacity : 34
character at position 3 is: i
sb after setting "a" at 3: thgan gnirud krab sgoD
StringBuilder Class:-
▪ Java 5 introduced a substitute of StringBuffer: the StringBuilder class.
▪ This class is faster than StringBuffer, as it is not synchronized.
▪ The line below shows
▪ the creation of a StringBuilder object.
▪ StringBuilder s=new StringBuilder();
▪ /* construct a StringBuilder object with an initial capacity of 16 characters.
▪ Similar to that of StringBuffer.*/