Menu
Topics Index
...
`

StringBufferBasics - Java Example Program


StringBufferBasics
class StringBufferBasics
{
    public static void main(String arg[])
    {
        StringBuffer sb = new StringBuffer("Merit Campus");
        sb.setCharAt(5, '*');  //LINE A
        System.out.println(sb);
        StringBuffer sb1 = new StringBuffer("C++,Html,C");
        sb1.replace(4, 8,"Java");    //LINE B
        System.out.println(sb1);
        StringBuffer sb2 = new StringBuffer("Merit");
        sb2.insert(2,'a');
        System.out.println(sb2);
    
    }
}
OUTPUT

Merit*Campus
C++,Java,C
Mearit

DESCRIPTION

In the above program, we initially created an instance of the StringBuffer class to hold the sequence of characters "Merit Campus". To replace any single character of the string, we can use setCharAt method which is shown in LINE A. To replace a sequence of characters, replace method can be used as shown in LINE B. To add characters at the end of the string, append method can be used and to insert characters in between the string insert method can be used. All these methods are available in different versions to enable us to add different types of data (float, int, double, char, boolean, String…). A version of insert is shown above, which inserts specified character at specified position.

THINGS TO TRY
  • Place the below code before LINE A and check the output. It should be Merit Campus online Java tutorial.
    sb.append(" online Java tutorial.");
    System.out.println(sb);
  • Place the below code before LINE A and check the output.
    sb.reverse();
    System.out.println(sb);

    The output should be supmaC tireM. Since the reverse method reverses each word in the String.

© meritcampus 2019

All Rights Reserved.

Open In App