StringBuffer Class in Java

  • By
  • January 12, 2022
  • JAVA Programming

StringBuffer Class in Java –

StringBuffer class in java is same as String, but Strings are immutable (no-changeable) whereas StringBuffer objects are mutable (changeable). Since, String are non changeable, the length should be same as capacity hence we don’t have the concept of capacity in StringBuffer. But in StringBuffer both capacity and length should be different.

Capacity is nothing but the number of characters that are accommodate in StringBuffer .

Length is nothing but the number of characters that are actually present in StringBuffer.

Constructors of StringBuffer –

  1.     StringBuffer sb=new StringBuffer();  

It creates empty StringBuffer with default initial capacity is 16 characters.  If 16 characters are completed and if we are trying to add 17th character then new StringBuffer object is created with big capacity (34 characters), all the 16 characters will be placed in that big capacity buffer and 17th char will also be placed. Again 34 characters get completed and if we are trying to add 35th character then big capacity buffer gets created having size 70.

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

Each and every time StringBuffer calculates its new capacity by the following formula.

                 new capacity=(current_capacity+1)*2

                                             =16+1*2

                                             =17*2

                                        =34

//program which creates empty StringBuffer object

package StringBufferEx;

public class SBConstructor {

public static void main(String[] args) {

//creates empty SB object with initial capacity is 16 character

        StringBuffer sb=new StringBuffer();  

        System.out.println(“default initial capacity is : “+sb.capacity());

        

//total 16 char is now entered and capacity is still 16 char

               sb.append(“asdfghjytredfgha”);                                                          System.out.println(“after entering 16 char capacity is : “+sb.capacity());

      // once 17th char is entered the new SB object gets create with capacity 34 char

                     sb.append(‘q’);                                                                                 

     // now capacity is 34char

               System.out.println(“current capacity is : “+sb.capacity());            

}

}

output :

default initial capacity is : 16

after entering 16 char capacity is : 16

current capacity is : 34

Constructor –

  1. StringBuffer sb=new StringBuffer(int initialCapacity)

  – User can specify his own capacity by using this constructor.

//program which creates StringBuffer object having capacity specified by the user

package StringBufferEx;

public class SBconstructor2

 {

      public static void main(String[] args) {

// creates string buffer object with the specified capacity provided i.e 10                 StringBuffer sb= new StringBuffer(10);                                                                   System.out.println(sb);                                                                            

//this prints empty string buffer because we are not appending any char till now.

          

           sb.append(“sdfgthujhg”);        // 10 character is appended to SB

System.out.println(“initial capacity is : “+sb.capacity());    //capacity is still 10

               sb.append(‘k’);                                                                                                                         //once 11th char is enter the new capacity object will be created with capacity 22

             System.out.println(“current capacity is : “+sb.capacity());          

}

}

output:

initial capacity is : 10

current capacity is : 22

Constructor –

  1. StringBuffer sb=new StringBuffer(String str);

-For given string create an equivalent SB object.

 //Program which creates SB object for given string

package StringBufferEx;

       public class SBconstructor3 {

    public static void main(String[] args) {

                       StringBuffer sb = new StringBuffer(“hello”);

//here SB capacity is= s.length+default initial capacity(i.e 5+16=21)

System.out.println(“current capacity is : “+sb.capacity());  

}

 

}

output: 

current capacity is : 21

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

Methods of StringBuffer

  1. public StringBuffer append(char a) 

  It appends specified character at the end of the original string

  1. public StringBuffer append(char str[])

It appends specified string of char array to the original string

3.public StringBuffer append(char str[],int iset, int ilength)

It appends specified string of char array to the original string

        str= name of the string which we want to append

       iset= index of the first char to append

        ilength=number of char to be append

  1. public StringBuffer append(String str)

    It appends specified string to the original string

//Program that shows the use of append method

 

package StringBufferEx;

public class SBappend_method {

         public static void main(String[] args) {

                         //Method1: append(char a)

         StringBuffer sb1=new StringBuffer(“good”);

           System.out.println(“sb1 = “+sb1.append(‘s’));   // char ‘s’ is appended to string “good”

                 //Method2: append(char[] astr)

         StringBuffer sb2=new StringBuffer(“good “);

         char astr[]= {‘h’,’a’,’b’,’b’,’i’,’t’};

            System.out.println(“sb2 = “+sb2.append(astr));  //char array astr is appended to sb2 object

       //Method3: append(char[] astr,int iset,int ilength)    

         StringBuffer sb3=new StringBuffer(“java is “);

         char bstr[]= {‘h’,’a’,’b’,’f’,’u’,’n’};

         System.out.println(“sb3 = “+sb3.append(bstr,3,3));  //char array bstr is appended to sb3 object starting from iset 3 and  append no of char 3

         //Method4: append(String str)

         StringBuffer sb4=new StringBuffer(“java is “);

        System.out.println(“sb4 = “+sb4.append(“object oriented”));  //String “object oriented is append to old string “java is”

         }

}

output:

sb1 = goods

sb2 = good habbit

sb3 = java is fun

sb4 = java is object oriented

  1. public StringBuffer insert(int offset,char c)

     Inserts the string representation of char argument into this sequence

     Offset means at which index position you want to insert elements

  1. public StringBuffer insert(int offset,string str)

     Inserts the string representation of char array argument into this sequence

  1. public StringBuffer insert(int offset,char c[])

     Inserts the string representation of char array argument into this sequence

  1. public StringBuffer insert(int offset,double db)

     Inserts the string representation of double argument into this sequence

//Program that shows the use of insert method

package StringBufferEx;

public class SBinsert {

public static void main(String[] args) {

                     //Method1 insert(int offset, char c)

                     StringBuffer sb1=new StringBuffer(“String”);

                     System.out.println(“sb1 = “+sb1.insert(6,’B’));       //insert char ‘B’ at 6th position of sb1 object

                     //Method2: insert(int offset, String str)

                     StringBuffer sb2=new StringBuffer(“String”);

                     System.out.println(“sb2 = “+sb2.insert(6,”Buffer”));   //insert string “buffer” at 6th position of sb1 object

                       //Method3: insert(int offset, char[])

                     StringBuffer sb3=new StringBuffer(“String”);

                     char str[]= {‘B’,’u’,’f’,’f’,’e’,’r’};

                     System.out.println(“sb3 = “+sb3.insert(6,str));       //insert char array str at 6th position of sb1 object

                     //Method4: insert(int offset, double db)

         StringBuffer sb4=new StringBuffer(“String”);

                     double d=0.1;

                     System.out.println(“sb4 = “+sb4.insert(6,d));   //insert double value d at 6th position of sb1 object

         }

}

output:

sb1 = StringB

sb2 = StringBuffer

sb3 = StringBuffer

sb4 = String0.1

  1. public StringBuffer replace(int start,int end,String str)

It replaces the characters in a substring of StringBuffer with character in specified string.

//Program that shows the use of replace method

package StringBufferEx;

public class SBreplace {

  public static void main(String[] args) {

      //Method1: replace(int start,int end,String str)

 StringBuffer sb=new StringBuffer(“javaprogramming “);

           System.out.println(sb.replace(4,15,”technology”));   //replace string

//”programming” in sb with new string “technology” within index position //between 4 to 15

} }

//output:

//javatechnology

  1. public StringBuffer delete(int startIndex,int endIndex)

   It  deletes string from startIndex to endIndex.

//Program that shows the use of delete method

package StringBufferEx;

public class SBdelete {

  public static void main(String[] args) {

           //Method1 delete(int start,int end)

StringBuffer sb=new StringBuffer(“javaprogramming “);

           System.out.println(sb.delete(4,15));                                                     //delete string in sb starting from 4 to 15

}}

//output:

//java

  1. public StringBuffer reverse()

   It reverses the current string of StringBuffer class.

//Program that shows the use of reverse method of StringBuffer

package StringBufferEx;

public class SBreverse {

public static void main(String[] args) {

                     //Method1 reverse()

         StringBuffer sb=new StringBuffer(“javaprogramming”);

               System.out.println(sb.reverse());                                                            }

}

//output:

// gnimmargorpavaj

  1. public StringBuffer capacity()

  It returns the capacity of StringBuffer. The default capacity of string buffer is 16 characters. 

//Program that shows the use of capacity() and length() method of StringBuffer

package StringBufferEx;

public class SBcapacity_method {

public static void main(String[] args) {

           //Method1: public int capacity()

                       StringBuffer sb1=new StringBuffer(“java1”);

                 System.out.println(“capacity = “+sb1.capacity());

                       //Method2: public int length()

                     StringBuffer sb2=new StringBuffer(“java1”);

                         System.out.println(“length = “+sb2.length());

                                 }

}

//output:

//capacity = 21

//length = 5

  1. public StringBuffer length()

   It returns the length of StringBuffer object.  

  1. public StringBuffer indexOf(String str)

   It returns the index of the specified string

  1. public StringBuffer indexOf(String str, int fromIndex)

   It returns the index of the specified string starting from fromIndex 

//Program that shows the use of capacity() and length() method of StringBuffer

//package StringBufferEx;

public class SBindexOf {

public static void main(String[] args) {

                     //method: int indexOf(String str)

         StringBuffer sb=new StringBuffer(“java programming lang”);

 System.out.println(sb.indexOf(“lang”));    //gives the index of “lang” string

         }

}

//output:

//17

  1. public StringBuffer setLength(int nlength)

It used to set the new length of the charsequence .The length of the new char sequence becomes to specified nlength.

//Program that shows the use of setLength() method of StringBuffer

package StringBufferEx;

public class SBsetLength {

public static void main(String[] args) {

                     //method: public void setLength(int newlength)

         StringBuffer sb=new StringBuffer(“java technology”);

           System.out.println(“given string : “+sb);

             System.out.println(“length of java technology string :”+sb.length());                                           

               sb.setLength(30);              //set new length of sb to 30                                                                                                               

 System.out.println(“set new length : “+sb.length());      //new length is 30

         System.out.println(sb);    //now, 30 characters are accommodate in sb

         }

}

//output:

//given string : java technology

//length of java technology string :15

//set new length : 30

//java technology          //now upto 30 chracters are accomodate in sb

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

  1. public void StringBuffer ensureCapacity(int minimum capacity)

This method ensures that the given capacity is the minimum to the current capacity. Means you can set your own capacity by using this method.

package StringBufferEx;

public class SBensureCapacity {

  public static void main(String[] args) {

         StringBuffer sb=new StringBuffer();

System.out.println(“initial capacity : “+sb.capacity()); //initial capacity 16 char

                     sb.ensureCapacity(17);           // as initial capacity is 16. we

//should specify the minimum capacity here i.e less than 16 but we specify //greater than 16, which cause to change currentcapacity by 34

   System.out.println(“capacity, after specifying first ensureCapacity() : “+sb.capacity());

                     sb.ensureCapacity(36);

                     System.out.println(“capacity, after specifying second ensureCapacity() : “+sb.capacity());

         }

}

/* output:

initial capacity : 16

capacity, after specifying first ensureCapacity() : 34

//capacity, after specifying second ensureCapacity() : 70  */

 

Author:-

Pooja Nandode-Bhavsar

Call the Trainer and Book your free demo class for now!!!

© Copyright 2020 | Sevenmentor Pvt Ltd.

 

 

Submit Comment

Your email address will not be published. Required fields are marked *

*
*