Programming Tutorials

insert() and reverse() in Java

By: Henry in Java Tutorials on 2007-09-12  


The insert() method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append(), it calls String.valueOf() to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms:

StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

Here, index specifies the index at which point the string will be inserted into the invokingStringBuffer object. The following sample program inserts "like" between "I" and "Java":

// Demonstrate insert().
class insertDemo {
    public static void main(String args[]) {
        StringBuffer sb = new StringBuffer("I Java!");
        sb.insert(2, "like ");

The output of this example is shown here:

I like Java!


You can reverse the characters within a StringBuffer object using reverse(), shown here: StringBuffer reverse()

This method returns the reversed object on which it was called. The following program demonstrates reverse():

// Using reverse() to reverse a StringBuffer.
class ReverseDemo {
    public static void main(String args[]) {
        StringBuffer s = new StringBuffer("abcdef");

Here is the output produced by the program:


Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)