insert( ) and reverse() in Java

By: Henry Viewed: 153712 times  Printer Friendly Format    


insert( )

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 ");
System.out.println(sb);
}
}

The output of this example is shown here: I like Java!


reverse()

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");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}

Here is the output produced by the program: abcdef
fedcba



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial