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, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

package org.kodejava.example.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
        System.out.println("quote = " + quote.toString());

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

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

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

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.example.lang;

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

        //  |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.
        sb.insert(4, "j");
        System.out.println("After first insert = " + sb.toString());

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

The program will print the following output:

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