StringBuffer In Java with Example

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();
    StringBuffer sb2 = new StringBuffer("I JAVA!");


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email