StringBuffer is a peer class of String that provides much of the functionality of the strings. String represents fixed-length, immutable character sequences. In contrast StringBuffer represents growable and writable character sequences. The StringBuffer provides 3 constructors which create, initialize and set the initial capacity of StringBuffer objects. This class provides many methods. For example the length() method gives the current length i.e. how many characters are there in the string, while the total allocated capacity can be found by the capacity() method.
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb =new StringBuffer("Hello");
System.out.println("buffer= " +sb);
System.out.println("length= " +sb.length());
System.out.println("capacity= " +sb.capacity());
//appending and inserting into StringBuffer.
String s;
int a = 42;
StringBuffer sb1= new StringBuffer(40);
s= sb1.append("a=").append(a).append("!").toString();
System.out.println(s);
StringBuffer sb2 = new StringBuffer("I JAVA!");
sb2.insert(2, "LIKE");
System.out.println(sb2);
}
}
Output Screen
buffer= Hi Rohit
length= 8
capacity= 24
a=42!
I LIKEJAVA!
No comments:
Post a Comment