How do I append and replace content of a StringBuffer?

A StringBuffer is like a String, but can be modified. StringBuffer are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

As of release JDK 1.5, this class has been supplemented with an equivalent class designed for use by a single thread, the StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all the operations, but it is faster, as it performs no synchronization.

package org.kodejava.lang;

public class StringBufferAppendReplace {
    public static void main(String[] args) {
        StringBuffer quote = new StringBuffer("an apple ");
        char a = 'a';
        String day = " day";
        StringBuffer sentences = new StringBuffer(" keep the doctor away");

        // Append a character into StringBuffer
        quote.append(a);
        System.out.println("quote = " + quote);

        // Append a string into StringBuffer
        quote.append(day);
        System.out.println("quote = " + quote);

        // Append another StringBuffer
        quote.append(sentences);
        System.out.println("quote = " + quote);

        // Replace a sub string from StringBuffer starting
        // from index = 3 to index = 8
        quote.replace(3, 8, "orange");
        System.out.println("quote = " + quote);
    }
}

Here is our program output:

quote = an apple a
quote = an apple a day
quote = an apple a day keep the doctor away
quote = an orange a day keep the doctor away

How do I insert a string to a StringBuffer?

package org.kodejava.lang;

public class StringBufferInsert {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("kodeava");
        System.out.println("Text before        = " + buffer);

        //  |k|o|d|e|a|v|a|....
        //  0|1|2|3|4|5|6|7|...
        //
        // From the above sequence you can see that the index of the
        // string is started from 0, so when we insert a string in
        // the fourth offset it means it will be inserted after the
        // "e" letter. There are other overload version of this
        // method that can be used to insert other type of data such
        // as char, int, long, float, double, Object, etc.
        buffer.insert(4, "j");
        System.out.println("After first insert = " + buffer);

        // Here we insert a string to the StringBuffer at index 8
        buffer.insert(8, " examples");
        System.out.println("Final result       = " + buffer);
    }
}

The program will print the following output:

Text before        = kodeava
After first insert = kodejava
Final result       = kodejava examples

How do I remove some characters from a StringBuffer?

The example below show you to remove some elements of the StringBuffer. We can use the delete(int start, int end) method call to remove some characters from the specified start index to end end index. We can also remove a character at the specified index using the deleteCharAt(int index) method call.

package org.kodejava.lang;

public class StringBufferDelete {
    public static void main(String[] args) {
        String text = "Learn Java by Examples";

        // Creates a new instance of StringBuffer and initialize
        // it with some text.
        StringBuffer buffer = new StringBuffer(text);
        System.out.println("Original text  = " + buffer);

        // We'll remove a sub string from this StringBuffer starting
        // from the first character to the 10th character.
        buffer.delete(0, 10);
        System.out.println("After deletion = " + buffer);

        // Removes a char at a specified index from the StringBuffer.
        // In the example below we remove the last character.
        buffer.deleteCharAt(buffer.length() - 1);
        System.out.println("Final result   = " + buffer);
    }
}

Output of the program is:

Original text  = Learn Java by Examples
After deletion =  by Examples
Final result   =  by Example

How do I reverse a string?

Below is an example code that reverse a string. In this example we use StringBuffer.reverse() method to reverse a string. In Java 1.5, a new class called StringBuilder also has a reverse() method that do just the same, one of the difference is StringBuffer class is synchronized while StringBuilder class is not.

And here is the string reverse in the StringBuffer way.

package org.kodejava.lang;

public class StringReverseExample {
    public static void main(String[] args) {
        // The normal sentence that is going to be reversed.
        String words =
                "Morning of The World - The Last Paradise on Earth";

        // To reverse the string we can use the reverse() method in
        // the StringBuffer class. The reverse() method returns a
        // StringBuffer so we need to call the toString() method to
        // get a string object.
        String reverse = new StringBuffer(words).reverse().toString();

        // Print the normal string
        System.out.println("Normal : " + words);
        // Print the string in reversed order
        System.out.println("Reverse: " + reverse);
    }
}

Beside using this simple method you can try to reverse a string by converting it to character array and then reverse the array order.

And below is the result of the code snippet above.

Normal : Morning of The World - The Last Paradise on Earth
Reverse: htraE no esidaraP tsaL ehT - dlroW ehT fo gninroM