StringBuffer

StringBuffer Java Example

In this example, we are going to present the StringBuffer class in Java, and StringBuffer vs StringBuilder which is contained in the java.lang package. We are going to show some of its most important uses and methods, and explain why and when it should be used, as well as the difference between StringBuffer and String.

1. String vs StringBuffer

Strings in Java are immutable. This means that when you instantiate a new String Object, you can not ever alter it. However, some of the most commonly seen code in Java happens to look like this:

String str = "hello";
str = str + " world";
//this prints "hello world"

So, what is going on here? Although it seems that we are appending to the String object, that in fact does not happen. What actually happens, is that the JVM creates a new StringBuffer object, which afterwards appends the different strings and in the end creates a new string, with a reference to the original. So essentially, we do not append a string to another, but we destroy the original String and use its variable to point to a whole new String (the concat of the first and the second one), which is also immutable.

Although it may seem that it is not a huge difference, it is in fact very important for optimization. While it is easier (and sometimes even advisable) to use the + operator for simplicity, when you have to do with a huge number of string concats you should try to use something like StringBuffer to make it faster. We will show the huge speed difference in the example later.

2. StringBuffer vs StringBuilder

Till Java 1.5 developers had a choice between String and StringBuffer. With Java 1.5 developers got a new option StringBuilder. In this section let us see the differences between StringBuffer and StingBuilder.

StringBufferStringBuilder
Thead safe as all methods are synchronisedNot thead safe, othewise it offers same features as StringBuffer
Offered as pat of Java early releasesIntroduced only in Java 1.5
Less performant as all methods are marked synchronisedOffers better performance than StringBuffer
StringBuffer Vs StringBuilder Table

If you operate in a single-threaded environment or don’t care about thead-safety then use StringBuilder.

3. StringBuffer constructors

StringBuffer offers below different constructors:

ConstructorExplanation
StringBuffer()Default constructor which allocates uninitialized StringBuffer of 16 characters capacity
StringBuffer(CharSequence seq)Constructs a StringBuffer with same contents as in input chracter sequence
StringBuffer(int capacity)Constructs an empty StringBuffer with specified capacity number of characters as capacity
StringBuffer(Sting s)Constructs a StringBuffer initialized with the specifie input String s
StringBuffer constructors Table

4. StringBuffer Java Example

Below Example depicts the usage of StringBuffer,

public class StringBufferMain {

    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer();
        
        // Append the string representation of the argument to the end of the buffer.
        // In this example we use a string, but the method also accepts int, float,
        // double, boolean, char (or char[]), as well as objects.
        buffer.append("Hello World!");
        System.out.println(buffer.toString());
        
        // Delete the specified substring by providing the start and the end
        // of the sequence.
        buffer.delete(5, 11);
        System.out.println(buffer.toString());
        
        // Delete just one char by providing its position.
        buffer.deleteCharAt(5);
        System.out.println(buffer.toString());
        
        // Insert a string in a specified place inside the buffer.
        buffer.insert(0, "World ");
        System.out.println(buffer.toString());
        
        // Get the index that the specified substring starts at.
        System.out.println("Index of Hello: " + buffer.indexOf("Hello"));
        System.out.println(); // Empty line
        
        
        
        // You can also instantiate a new StringBuffer and provide
        // the initial String in the constructor.
        StringBuffer newBuffer = new StringBuffer("This is a Hello World string. Hello!");
        
        // You can use lastIndexOf(String) to get the last time that a specified
        // substring appears in the StringBuffer.
        System.out.println("Index of Hello: " + newBuffer.indexOf("Hello"));
        System.out.println("Last index of Hello: " + newBuffer.lastIndexOf("Hello"));
        
        // You can also replace a specific sub-sequence of the StringBuffer with another string.
        // The size does not need to be the same, as shown here.
        newBuffer.replace(0, 4, "That here");
        System.out.println(newBuffer.toString());
        
        // You can replace a single char using this method here. We want to
        // replace the last character of the string, so instead of counting the length,
        // we will use the provided length() method, and replace the char in the last index.
        newBuffer.setCharAt(newBuffer.length() - 1, '?');
        System.out.println(newBuffer.toString());
        
        // You can reverse the StringBuffer as well!
        newBuffer.reverse();
        System.out.println(newBuffer.toString());
        
        
        compareTime();
    }

    private static void compareTime() {
        long startTime;
        String str = "";
        StringBuffer buffer = new StringBuffer();
        
        // Using String
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            str += "extra";
        }
        System.out.println("Time using String: "
                + (System.currentTimeMillis() - startTime) + " ms.");
        
        // Using StringBuffer
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            buffer.append("extra");
        }
        System.out.println("Time using StringBuffer: "
                + (System.currentTimeMillis() - startTime) + " ms.");
    }
}

The first thing that you need to draw your attention to is the time output (the last 2 lines). You can see an enormous difference in time, which makes it pretty clear that Stringbuffer is the recommended approach when you have to deal with a large number of strings (in our example it is 10000). 488 ms vs. 2 ms makes a whole lot of a difference, especially in heavy applications, where 10000 strings might be the minimum threshold.

StringBuffer Java - Output
Output

Secondly, let’s take a look at some of the most interesting and important StringBuffer methods, which were used in the example:

  • append(String str): This method is used to add a string in the end of the StringBuffer. You can also use other versions of this method, such as append(int), where the String representation of the int will be added.
  • delete(int start, int finish): Delete the specified substring from the StringBuffer.
  • deleteCharAt(int position): Delete the character at the specified position.
  • setCharAt(int position, char c): Replace a character in the StringBuffer.
  • insert(int start, String str): insert a new string anywhere you want in the StringBuffer, by using the first argument of the method as the starting position of the new string.
  • replace(int start, int finish, String str): You can replace a whole substring with another string in the StringBuffer. The inserted string does not need to be of the same size, which makes this method incredibly useful.
  • reverse(): Reverses the whole StringBuffer (first character becomes last etc).

Of course, there are many more methods and functionality, but more or less most of them are variations of the ones presented here. By having the above methods in mind you can make use of all the important parts of StringBuffer and make your String manipulation faster, more optimized and simpler in many cases.

5. Download the source code

This was an example of StringBuffer use in Java.

Download
You can download the example here: StringBuffer Java Example

Last updated on May 25th, 2020

Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Fahd
Fahd
6 years ago

Hello, can you please explain why you didn’t use stringBuilder?
StringBuffer is the same but all its methods are synchronized.

Back to top button