Ilias Koutsakis

About 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.

Java StringBuffer Example

In this example we are going to present the StringBuffer class, 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!" // 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 Example

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.");
    }
}

Output:

Hello World!
Hello!
Hello
World Hello
Index of Hello: 6

Index of Hello: 10
Last index of Hello: 30
That here is a Hello World string. Hello!
That here is a Hello World string. Hello?
?olleH .gnirts dlroW olleH a si ereh tahT
Time using String: 488 ms.
Time using StringBuffer: 2 ms.

The first thing that you need to draw your attention on 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.

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.

3. Download the example

This was an example of StringBuffer use in Java.
You can download the example here: StringBufferExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close