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

How to use the StringBuffer class in Java

In this article, we will learn about StringBuffer class, advantages of StringBuffer class, and then in the end use it as a tool in our program.

StringBuffer class is available in java.lang package. StringBuffer is a sequence of characters, which is mutable. In other words, it is a sequence of characters which can be changed with the help of various methods available in the class.

A StringBuffer Object can be created in the following ways:

1. Without any capacity (or) character sequence

StringBuffer stringBuffer1 = new StringBuffer();

2. With a capacity

StringBuffer stringBuffer2 = new StringBuffer(10);

3. With a character sequence

StringBuffer stringBuffer3 = new StringBuffer(",Thank You, visit again!");
stringbuffer

Figure 1: Stringbuffer

Step 1: In this step, we will create a simple program to understand the StringBuffer class and make use of some of its methods.

Listing 1: Code to execute Step 1

 // import statements
    import java.lang.StringBuffer;
    public class StringBufferExample {
    // StringBuffer without any capacity (or) character sequence
    StringBuffer stringBuffer1 = new StringBuffer();
    // StringBuffer with a capacity
    StringBuffer stringBuffer2 = new StringBuffer(10);
    //StringBuffer with a character sequence
    StringBuffer stringBuffer3 = new StringBuffer(",Thank You, visit again!");
  
   char charSingle = 'A';
    char dummy = 'x';
    String error = "ERROR";
    char[] charArray = {'c', 'o', 's', 't', 's'};
    double cost = 990.99;
    int serviceCharges = 9;

// The below method returns a new StringBuffer 
    public StringBuffer createString(String someString) {
   // appending variables of different datatypes 
        stringBuffer1.append(charSingle);
        stringBuffer1.append("\t");
        stringBuffer1.append(someString);
        stringBuffer2.append("\twith service charges");
        stringBuffer1.append(stringBuffer2);
        stringBuffer1.append("\t");
        stringBuffer1.append(dummy);
        stringBuffer1.append(charArray);
        stringBuffer1.append("\t");
        stringBuffer1.append(error);
        stringBuffer1.append(cost);
        stringBuffer1.append(stringBuffer3);
        return stringBuffer1;
    }

  
// The below method removes the unwant characters in the StringBuffer and returns the same StringBuffer
  public StringBuffer removeUnwanted(StringBuffer errorString) {
        int errorStringindex = stringBuffer1.indexOf("ERROR");
        int errorCharIndex = stringBuffer1.indexOf("x");
        System.out.println("Length of the String--" + stringBuffer1.length() + "\n");
        System.out.println("Position of Unwanted String: Index--" + errorStringindex);
        System.out.println("Position of Unwanted Character: Index--" + errorCharIndex + "\n");
        stringBuffer1.delete(46, 51);
        stringBuffer1.deleteCharAt(39);
        System.out.println("Length of the String now, after deletion of unwanted characters--" + stringBuffer1.length() + "\n");
        return stringBuffer1;
    }

// The below method replaces some characters in the StringBuffer and returns the same StringBuffer
    public StringBuffer replaceNew(StringBuffer finalString) {
        int replaceStringindex = stringBuffer1.indexOf("with service charges");
        System.out.println("Position of String that has to be replaced: Index--" + replaceStringindex);
        stringBuffer1.replace(17, 38, "\twithout service charges");
        return stringBuffer1;
    }
    public static void main(String args[]) {
        StringBufferExample stringBufferExample = new StringBufferExample();
        StringBuffer outputStringBuffer = stringBufferExample.createString("set of HP Books");
        System.out.println(outputStringBuffer + "\n");
        StringBuffer newoutputStringBuffer = stringBufferExample.removeUnwanted(outputStringBuffer);
        System.out.println(newoutputStringBuffer);
        StringBuffer finaloutputStringBuffer = stringBufferExample.replaceNew(newoutputStringBuffer);
        System.out.println("\n" + finaloutputStringBuffer);
String stringoutput=finaloutputStringBuffer.toString();
    }
}

Running this program will give us the following output:

A set of HP Books with service charges xcosts ERROR990.99,Thank You, visit again!

Length of the String--81

Position of Unwanted String: Index--46
Position of Unwanted Character: Index--39

Length of the String now, after deletion of unwanted characters--75

A set of HP Books with service charges costs 990.99,Thank You, visit again!
Position of String that has to be replaced: Index--18

A set of HP Books without service charges costs 990.99,Thank You, visit again!

Let us analyze the above program step by step:

In the first line of the code, we are importing the ‘StringBuffer’ class which is available in ‘java.lang’ package.

Inside the class we are creating three StringBuffer objects, first without character sequence and capacity, second with capacity and third with character sequence. In the ‘createString(String someString)’ method we keep on appending values of different datatypes to ‘stringBuffer1’.

We are also appending another StringBuffer to ‘stringBuffer1’. In the output we get:

A set of HP Books with service charges xcosts ERROR990.99,Thank You, visit again!

The above StringBuffer has an unwanted character ‘ x’ and an unwanted word ‘ERROR’ in between, which was appended to it in the ‘createString(String someString)’ method .

The method ‘removeUnwanted(StringBuffer errorString)’ method removes the unwanted character and the word by getting the index value of the unwanted character and start and end index values of the word, thus reducing the StringBuffer size from 81 to 75, which we are printing in the console.

Now when we print the StringBuffer it prints:

A set of HP Books with service charges costs 990.99,Thank You, visit again!

The method ’replaceNew(StringBuffer finalString)’ simply gets the latest StringBuffer and replaces some values again, with the help of start and end index values of the word that has to be replaced. We get the below output:

A set of HP Books without service charges costs 990.99,Thank You, visit again!

At the end of the program, we are converting the StringBuffer object to a String object by using ‘toString()’. Other than these methods, the StringBuffer class has got lot more methods.

Step 2: In this step, we will create a simple program to understand some more methods of the StringBuffer class .

Listing 2: Code to execute Step 2

// import statements
import java.lang.StringBuffer;
public class StringBufferExample2 {
StringBuffer stringBuffer=new StringBuffer("The Chamber of Secrets");
public void manipulate(){
// printing the StringBuffer
System.out.println("The given String is:"+stringBuffer);
// getting the substring of the StringBuffer
System.out.println("The Story is about a:"+stringBuffer.substring(4,12));
// getting the reverse of the StringBuffer
System.out.println("The Reverse of the given String is:"+stringBuffer.reverse());
}
public static void main(String args[]){
    StringBufferExample2 stringBufferExample2=new StringBufferExample2();
    stringBufferExample2.manipulate();
}
}

Running this program will give us the following output:

The given String is:The Chamber of Secrets

The Story is about a:Chamber

The Reverse of the given String is:sterceS fo rebmahC ehT

In the above output, the first line is the sequence of characters from the StringBuffer as such; the second line contains the substring of the StringBuffer. A substring of a StringBuffer is the sequence of characters which come between the specified index of the StringBuffer.

In our case we have ‘stringBuffer.substring(4,12)’. So it is the sequence of characters that comes between 4 and 12. We can also get a substring by just giving the start index alone. In this case the substring is the sequence of characters which comes after the specified start index.

In the third line of the output, we have the reverse of the sequence of characters from the StringBuffer.

In both of the above examples, we can note that the same StringBuffer is manipulated again and again. We are not creating new objects for each manipulation. Thus StringBuffer is considered as mutable.

Conclusion

In this article, we have learnt about the StringBuffer class and the advantages of using the StringBuffer class. We have also implemented the StringBuffer class and some of the methods available in StringBuffer class in our code.



I have done my bachelor in Computer Science and I am well versed with programming languages such as JAVA, C#, html and done courses on Android development.

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