Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java StringBuffer: Overview

Here in this article we are going to learn about StringBuffer and StringBuilder that provide a mutable String in java.

We all are familiar with String. String is the core part of any programming language. String is nothing but the sequence of characters. Java provides String class to use String. But there are some restrictions in String class. We cannot modify String instance once it is created. String is immutable in java. To ignore these limitations and to fullfill the requirement of string manipulation. Java provides two classes for string modification:

  1. StringBuilder.
  2. StringBuffer.

1. StringBuilder

String Builder class was introduced in J2SE 5 to enhance java’s powerful String features. StringBuilder is mutable, which means we can modify the content of StringBuilder Object. StringBuilder is similar to StringBuffer class but there is only one main difference.

StringBuffer is synchronized while StringBuilder is not. We can say that StringBuilder class is not thread safe hence its performance is better compared to StringBuffer. As StringBuilder class is not thread safe we should not use this class where we are using multi-threading concepts.

We can create StringBuilder class object using its sonstructors. There are mainly four constructors to create StringBuilder class in different ways.

All of them are listed below with their syntax:

  • Default Constructor.
    Syntax:
    StringBuilderobjectName=new StringBuilder();

    This Constructor creates StringBuilder instance with an empty value. It has a capacity of 16.
  • Constructor with CharSequence.
    Syntax:
    StringBuilderobjectName = new StringBuilder(CharSequencecharSequenceObject);
    This constructor create StringBuilder object with specified CharSequence Object. It also adds extra 16 empty elements.
  • Constructor with Integer Argument
    Syntax:
    StringBuilderobjectName=new StringBuilder(intcapacityofbuilder);
    This constructor creates an object with empty string and specified the capacity of StringBuilder Object.
  • Constructor with String Argument.
    Syntax:
    StringBuilderobjectName=new StringBuilder(String stringObjectToInitialize);
    This constructor creates an object with given String object value and also adds extra 16 empty elements.
    Above listed are four different constructors that are used to build a StringBuilder object.

StringBuilder class Example Given Below.

Listing 1: StringBuilderExample.java

  public class StringBuilderExample {
  public static void main (String[] args)
        {
                   String stringToInititalizeStringBuilder; // String Object to initialzeStringBuilder Object..
                   stringToInititalizeStringBuilder="This String Is Initialzed using String Builder...";
                   
                   
                   StringBuilderstringBuilderObject=new StringBuilder(); // Created Using Default Constructor...
                   
                   System.out.println("\n\t Length Of StringBuilder Object 1:- "+ stringBuilderObject.length());
                   
                   stringBuilderObject.append("Hello Sample");
                   
                   StringBuilder stringBuilderObject2=new StringBuilder(stringToInititalizeStringBuilder);
                   
                               
                   System.out.println("\n\t Length Of StringBuilder Object 2:- "+ stringBuilderObject2.length());
                   
                   
                   System.out.println("\n\t"+stringBuilderObject2);
                   
                   
                   System.out.println("\n\t Reverse String Using String Builder class Method:-  "+ stringBuilderObject.reverse());
     
                   }
   }

OutputListing 1: StringBuilderExample.java

Length OfStringBuilder Object 1:- 0

Length OfStringBuilder Object 2:- 49

This String Is Initialzed using String Builder...

Reverse String Using String Builder class MethodelpmaSolleH

The above example illustrates constrcutor use to create Object of StringBuilder class. In this example one StringBuilder class method is used. reverse() method of StringBuilder class method is used to reverse the String content. This example simply demonstrate the use of Stringbuilder class.

2. StringBuffer

StringBuffer class is just like String class that provides many functionalities of String class.

String is immutable while StringBuffer is mutable. String class in Java represents fixed length character sequence while StringBuffer does not have fixed length. When we use StringBuffer we can modify String, append characters to it, we can expand string etc. StringBuffer automatically expands when it is modified. It provides room to add new character and modify the String.

The same way it does for the String class, java provides different constructors of StringBuffer class to create object of StringBuffer.

  1. Default Constructor to create StringBuffer instance with empty value.
    Syntax:
    StringBufferstringBufferObjectName=new StringBuffer();
    Here in above syntax we create StringBuffer instance with an empty value. When we create object with default constructor then by default it will reserve memory for 16 characters.
  2. Constructor with Integer Argument to Set Size Of an StringBuffer.
    Syntax:
    StringBufferobjectName=new StringBuffer(intsizeofBuffer);
    Here in above declaration we use constructor that specifies the size of the StringBuffer object. sizeOfBuffer provides integer value. We explicitly set size of an instance by using these constructors.
    Listing 2: StringBufferConstructorExample.java
    public class StringBufferConstructorExample {
    
    public static void main (String[] args)
                {
                            StringBufferstringBufferObject=new StringBuffer(); // Defaul Constructor.
                           
                            System.out.println("\n Length Of StringBuffer object created using Default Constructor :- "+ stringBufferObject.length());
                           
                           
                            StringBuffer stringBufferObject2=new StringBuffer(10);
                           
                            String stringToAddInStringBuffer="This String Added into String Buffer..";
                           
                            stringBufferObject2.append(stringToAddInStringBuffer);
                           
                            System.out.println("\nLength Of StringBuffer object created By specifying Size in Constructor :- "+ stringBufferObject2.length());
    System.out.println("\n\t"+ stringBufferObject2);
                            }
     
    }
    

    Output Listing 2: StringBufferConstructorExample.java
    Length Of StringBuffer object created using Default Constructor :- 0
    Length Of StringBuffer object created By specifying Size in Constructor :- 38
    This String Added into String Buffer..
    The above example illustrates the use of both default and integer size constructor of String Buffer. When we initialize instance with default constructor the length of an instance is 0. Same thing happens when you initialize instance with specifying integer size. Both constructors work similarly. We use append method to append data into StringBuffer instance. We also can pass String class object inside append method. Here, we see that we add String class object to StringBuffer instance.]
  3. Constructor that create and initialize instance with given string.
    Below syntax Shows the constructor that we use to create object of StringBufferclass with specifying String.

    Syntax:
    StringBufferobjectName=new StringBuffer(String stringObjecttoInitialize);
    Here in above syntax we pass String object as an argument to StringBuffer constructor. objectName instance initialize with value of String Object that we pass.

  4. Constructor with Characacter Sequence.

    Syntax:
    StringBufferobjectName=new StringBuffer(CharSequence characters);
    Here in this constructor we pass character sequence as an argument to initialize instance with the passing value.

Example of both Constructor is Given Below.

Listing 3: StringBufferConstructorExample.java

  public class StringBufferConstructorExample {
  

  public static void main (String[] args) 
        {
                    String stringToInitializeBuffer; // String Object used to Initialize StringBuffer..
                   CharSequencecharSequenceToAddInConstructor; // CharSequence instance To Initialize StringBuffer..
     
                   stringToInitializeBuffer="This Initialization done using String Object";
   
                   charSequenceToAddInConstructor="This Initialization Done Using CharSequence..";
                   
                   
                   StringBufferstringBufferObject=new StringBuffer(stringToInitializeBuffer); // use Of Constructor  that take String object Argument..
                   
                   System.out.println("\n\t"+ stringBufferObject);
                   
                   StringBuffer stringBufferObject2=new StringBuffer(charSequenceToAddInConstructor); // use Of Constructor  that take CharSequence instance Argument..
                   
                   System.out.println("\n\t"+ stringBufferObject2);
        
                   }
   }

Output Listing 3:StringBufferConstructorExample.java

This Initialization done using String Object

This Initialization Done Using CharSequence..

In above example we create StringBuffer instance in two different ways. First constructor has String object as an argument and another one has CharSequence type of argument. We initialize instance with given String. This is the simple example that illustrates the use of different constructors that used to create StringBuffer object.

Methods Of StringBuffer class.

Like String class StringBuffer class has number of methods. Some of them are similar as String class. By using methods of StringBuffer class we achieve modification of String content. Some methods are listed below.

append() Method:

This method is use to append the value to the last of StringBuffer object. This method returns a StringBuffer. There are many overloaded methods are available in StringBuffer Class that are listed below.

General Syntax of StringBuffer class append() Method :

StringBufferappend(argument);

Different kinds of Overloaded Methods of append() method are :

append(booleanboolVal);

This method appends the boolean value to the StringBuffer Object.

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          strBuffer.append(true);
                          System.out.println("String in String Buffer :" + strBuffer);
              }

output :

String in String Buffer :HEllo true

append(char c);

This method appends a character value to the StringBuffer Object.

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          strBuffer.append('M');
                          System.out.println("String in String Buffer :" + strBuffer);
               }

output :

String in String Buffer :HEllo M

append(char[] charArr) ;

This method appends the array of type char in the StringBuffer Object.

i.e. :

              public static void main(String[] args)
              {          
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append  : String in String Buffer :" + strBuffer);
                          char [] charArr={'G','o','o','d','M','o','o','r','i','n','g'};
                          strBuffer.append(charArr);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append: String in String Buffer :HEllo

After append :String in String Buffer :HElloGoodMooring

append(char[] charArr,intoffset,int length);

This method appends the selected value of the array of type char in the StringBuffer Object.

i.e. :

              public static void main(String[] args)
               { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append : String in String Buffer :" + strBuffer);
                          char [] charArr={'G','o','o','d','M','o','o','r','i','n','g'};
                          strBuffer.append(charArr,3,6);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append: String in String Buffer :HEllo

After append : String in String Buffer :HEllodMoori

append(double d);

This method appends the double type value in a StringBuffer Object.

i.e. :

                          public static void main(String[] args)
   { 
                                     StringBufferstrBuffer=new StringBuffer("HEllo ");
                                     System.out.println("Before append : String in String Buffer :" + strBuffer);
                                     strBuffer.append(200.0);
                                     System.out.println("after append : String in String Buffer :" + strBuffer);
                          }

output :

Before append: String in String Buffer :HEllo

After append : String in String Buffer :HEllo 200.0

append(flaot f);

This method appends the float type value in a StringBuffer Object.

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append : String in String Buffer :" + strBuffer);
                          strBuffer.append(33.0f);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append: String in String Buffer :HEllo

After append : String in String Buffer :HEllo 33.0

append(int i);

This method appends int value to the StringBuffer Object.

i.e. :

  public static void main(String[] args)
              {          
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append : String in String Buffer :" + strBuffer);
                          intintValue=20;
                          strBuffer.append(intValue);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append : String in String Buffer :HEllo

after append : String in String Buffer :HEllo 20

append(long lngValue);

This method is append long value to the StringBuffer Object.

i.e. :

              public static void main(String[] args)
  { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append : String in String Buffer :" + strBuffer);
                          longlngValue=200000;
                          strBuffer.append(lngValue);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append: String in String Buffer :HEllo

After append : String in String Buffer :HEllo 200000

append(String strValue);

This method is append String value to the StringBuffer Object.

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append : String in String Buffer :" + strBuffer);
                          String strValue="How R U !!";
                          strBuffer.append(strValue);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append: String in String Buffer :HEllo

After append : String in String Buffer :HEllo How R U !!

append(StringBufferstrBuffer);

This method is append StringBuferonject to the StringBuffer Object.

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo ");
                          System.out.println("Before append : String in String Buffer :" + strBuffer);
                          StringBufferstrBufferValue=new StringBuffer("How R U ... ?");
                          strBuffer.append(strBufferValue);
                          System.out.println("after append : String in String Buffer :" + strBuffer);
              }

output :

Before append: String in String Buffer :HEllo

After append : String in String Buffer :HEllo How R U ... ?

capacity() Method :

This method returns the current Capacity of the StringBuffer Class. this method return an int(integer) value.

Syntax :

stringBufferObj.capacity();

i.e. :

              public static void main(String[] args)
  { 
                          StringBufferstrBuffer=new StringBuffer("HEllo how r u");
                          System.out.println("Capacity of strBuffer is :" + strBuffer.capacity());
              }

output :

Capacity of strBufferis :29

charAt() Method :

This method is used to get a character from StringBuffer of particular index. this method returns the char (character) value.

i.e .:

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo how r u");
                          System.out.println("Character at position 7 is:" + strBuffer.charAt(7));
              }

output :

Character at position 7 is:o

delete() Method;

This method is used to remove a substring from the StringBuffer Object. This method returns the StringBuffer Object.

Syntax :

strBuffrerObj.delete(intstartIndex,intendIndex);

herestartIndex is the starting index of the removing Character sequence and endIndex is the ending or how long character you want to remove from stringBuffer Object.

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo how r u");
                          System.out.println("BEfore delete  : StringBuffer is :" + strBuffer);
                          strBuffer.delete(3,7);
                          System.out.println("After delete : StringBuffer is :"+strBuffer);
              }

output :

BEforedelete :StringBuffer is :HEllo how r u

After delete :StringBuffer is :HElow r u

deleteCharAt() method :

This method is used for delete a particular character by particular given index. This method returns StringBuffer object.

Syntax :

strBufferObj.deleteCharAt(int index)

i.e. :

              public static void main(String[] args)
              { 
                          StringBufferstrBuffer=new StringBuffer("HEllo how r u");
                          System.out.println("BEfore delete  : StringBuffer is :" + strBuffer);
                          strBuffer.deleteCharAt(7);
                          System.out.println("After delete : StringBuffer is :"+strBuffer);
              }

output :

BEforedelete :StringBuffer is :HEllo how r u

After delete :StringBuffer is :HEllohw r u

length() method :

This method is returns the total number of character in StringBuffer Object. This method returns an int value.

i.e.:

              public static void main(String[] args)
      { 
                          StringBufferstrBuffer=new StringBuffer("HEllo how r u");
                          System.out.println("StringBuffer length is :" + strBuffer.length());
              }

output :

StringBuffer length is :13

reverse() Method :

This method reverses the Value of StringBuffer Object . This method returns the StringBuffer Object.

i.e. :

  public static void main(String[] args)
  {          
              StringBufferstrBuffer=new StringBuffer("HEllo how r u");
              strBuffer.reverse();
              System.out.println("StringBuffer length is :" + strBuffer);
  }

output :

StringBuffer length is :u r wohollEH

insert() Method :

This method is used to insert a value to the particular offset in the StringBuffer Class. This Method Returns StringBuffer Object.

There Many overloaded Methods are available in the StringBuffer Class are Listed below.

  • insert(intoffset,booleanbValue);
  • insert(intoffset,charchr)
  • insert(intoffset,char []charArr)
  • insert(intindex,char [] chr,intoffset,intlen)
  • insert(intoffset,doubledValue)
  • insert(intoffset,floatfValue)
  • insert(intoffset,intiValue)
  • insert(intoffset,longlValue)

i.e. :

  public static void main(String[] args)
   { 
                          StringBufferstrBuffer=new StringBuffer("HEllo how r u");
                          strBuffer.insert(3,"hello");
                          strBuffer.insert(6,true);
                          strBuffer.insert(6,20f);
                          System.out.println("StringBuffer after Insert value is :" + strBuffer);
  }

output :

StringBuffer length is :HElhel20.0truelolo how r u

There are many more useful metod available in the StringBuffer is Listed below.

  • indexOf();
  • lastIndexOf();
  • substring();
  • trimToSize();
  • ensureCapacity();

Above listed Methods work as their name implies. We used them to find an index or extract substring or trimming String.

Conclusion:

In this Article we learn StringBuilder and SrtingBuffer classes and their methods.

We got an idea about mutable and immutable strings.



Computer system engineer who has 4 year of experience in the field our web-development ,FPGA, and java programming.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login