String Buffer in Java

String Buffer:

  •    It is a final class in java.lang package which contains collection of character like String.
  •    String objects are immutable(can’t be modify) where as string buffer objects are mutable(can be modify)
  •    We can create the string buffer object using new operator. we can’t create string buffer object without new operator like string because of this there is no reusability of string buffer object like string object(with string constant pooling).
Example:
Let see the example with details:

 class St
{
public static void main(String as[])
{
StringBuffer sb1=new StringBuffer();
System.out.println(sb1.length());   // 0
System.out.println(sb1.capacity()); // 16

StringBuffer sb2=new StringBuffer("Hello");
System.out.println(sb2.length());   //5
System.out.println(sb2.capacity());  //16+5


sb2.append("rajiv");
System.out.println("--AFTER APPEND---");
System.out.println(sb2.length());   //5+5
System.out.println(sb2.capacity());
StringBuffer sb3=new StringBuffer("Hello");
System.out.println(sb3);
sb3.reverse();
System.out.println(sb3);    //olleH
sb3.insert(3,"raman");
System.out.println(sb3);    //ollramaneH
sb3.delete(2,6);
System.out.println(sb3);
}
}

OUTPUT:
java St
0
16
5
21
--AFTER APPEND---
10
21
Hello
olleH
ollramaneH
olaneH







0 comments :

Post a Comment