StringBuffer Functions with examples

In our last blog, we understand different and similarity of String Functions and StringBuffer Functions. In this blog, we will see example of StringBuffer class and functions.

 

List of StringBuffer Functions

FunctionsFunction’s Work
reverse()To reverse String
setCharAt(int,char)To replace index character
insert(int,String)To add extra string in index
append()To join two string
delete(int,int)To remove index to index string
deleteCharAt(int)To remove character from index

 

Let’s see example on all functions

class str9

{

            public static void main(String args[])

            {

                        StringBuffer str1 = new StringBuffer(“Welcome in StringBuffer”);

 

                        //StringBuffer str2 = “Demo Text”; // Generate Error…..

                        // Not possible in StringBuffer Class

 

                        // reverse

                        System.out.println(str1.reverse());

                        // setCharAt(int,char)

                        str1.reverse();

                        str1.setCharAt(4,’X’);   // Change o to X

                        System.out.println(str1); // WelcXme in StringBuffer

 

 

                        // insert(index,””)

                        str1.insert(5,”Demo Text”);      // add Extra string at 5th index

                        System.out.println(“\n\n”+str1);

 

                        // append()

                        str1.append(“Add Extra Text”);

                        System.out.println(“\n\n”+str1);

 

                        // delete

                        str1.delete(5,10);// remove 5th index to 10th index string

                        System.out.println(“\n\n”+str1);

 

                        // deleteCharAt(int)

                        System.out.println(str1.deleteCharAt(0));// remove 1st index char from stringbuffer

            }

}

 

Output

reffuBgnirtS ni emocleW

WelcXme in StringBuffer

 

WelcXDemo Textme in StringBuffer

 

WelcXDemo Textme in StringBufferAdd Extra Text

 

WelcXTextme in StringBufferAdd Extra Text

elcXTextme in StringBufferAdd Extra Text

2035total visits,6visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image