insert( ) and reverse() in Java

By: Henry  

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 ");

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: abcdef

Archived Comments

1. Very simple and nice way to explain the code. Thank you
View Tutorial          By: akshay at 2013-11-25 09:24:27

2. This Tutorial Rocks!kip it up
View Tutorial          By: Chuck Chalc at 2010-04-22 02:44:11

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial