Using the StringBuffer class


Since strings are immutable, you may want to use the StringBuffer class if you're going to alter the String in the code. The StringBuffer class can be seen as a mutable String object which allocates more memory (or deallocates if told so) when it's content is altered.
It should be said early that the StringBuffer class i thread-safe which means that it automatically handles synchronization of access to the object by different threads.
If you're using only one thread in your program you should use the StringBuilder class instead since it's pretty much identical to the StringBuffer class except that it doesn't handle synchronization.

A StringBuffer object has an attribute called capacity that determines how many bytes that are allocated in the buffer. You can specify at construction time which capacity it should start out with.
When you later add bytes to the buffer it will automatically increase the capacity of the array.
If you don't specify any capacity at all it will still allocate 16 bytes by default, so if we had a method like this:


    /**
     * Creates a few StringBuffer objects with different capacities
     */

    public void capacityExample() {
        
        StringBuffer buffer1 = new StringBuffer();
        StringBuffer buffer2 = new StringBuffer(0);
        StringBuffer buffer3 = new StringBuffer(100);
        
        System.out.println(buffer1.capacity());
        System.out.println(buffer2.capacity());
        System.out.println(buffer3.capacity());
        
    }


...the output would be:

16
0
100

There are also overloaded constructors of the StringBuffer class that takes a String and a CharSequence object as arguments.


To add text to a StringBuffer object you can either add it to the end of the buffer using the append method, or you can specify at what point you want the text to be inserted by using the insert method.
This method shows how to use them both:


    /**
     * Creates a few StringBuffer objects and uses the append and
     * insert methods to add text to them.
     * We use the \n character for line breaks.
     */

    public void insertTextExample() {
        
        //Create the StringBuffer
        StringBuffer buffer = new StringBuffer("Line 1\n");
        
        //Append text to the end of the buffer
        buffer.append("Line 3\n");
        
        //Now we want to add text in between line 1 and line 3
        String lineToInsert = "Line 2\n";
        int index = buffer.indexOf("Line 3");
        buffer.insert(index, lineToInsert);
        
        System.out.println(buffer.toString());
        
    }


The output of the insertTextExample method above will be:

Line 1
Line 2
Line 3

Now, consider we want to delete text from the StringBuffer. For simplicity we use the same code as above to construct the StringBuffer and then we delete the same text as we just added:


    /**
     * Deletes text from the StringBuffer object
     */

    public void deleteTextExample() {
        
        //Create the StringBuffer
        StringBuffer buffer = new StringBuffer("Line 1\n");
        
        //Append text to the end of the buffer
        buffer.append("Line 3\n");
        
        //Now we want to add text in between line 1 and line 3
        String lineToInsert = "Line 2\n";
        int index = buffer.indexOf("Line 3");
        buffer.insert(index, lineToInsert);
        
        System.out.println(buffer.toString());
        
        //Now we want to delete the text we just inserted
        //Note that the method returns a new instance of StringBuffer
        buffer = buffer.delete(index, index + lineToInsert.length());

        System.out.println(buffer.toString());
        
    }


The output of the method above will be:

Line 1
Line 2
Line 3

Line 1
Line 3

There are several methods in the StringBuffer class and this example just bring up a few of them, perhaps though the ones mostly used.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: