• August 28, 2014
  • Core Java
  • Comments Off on insert(int offset, String str) StringBuffer method in java

insert(int offset, String str) StringBuffer method in java

insert(int offset, String str): insert specified string at the offset indicated position.

Syntax: public synchronized StringBuffer insert(int offset, String str).

Note: if specified string is null than it insert “null” string at the offset indicated position.
If insert has object, int, double etc instead of string than argument value first converted into string using String.valueOf()before inserting.
Offset should be between 0 to length of string, if it is not StringIndexOutOfBoundsException will be thrown.

Example:

StringBufferInsertExample.java

/**
 * This program is used to show the use of insert() method.
 * @author javawithease
 */
class TestStringBuffer{
	StringBuffer sb = new StringBuffer("www.com");
 
	/**
	 * This method is used to show the use of insert() method.
	 * @author javawithease
	 */
	public void insertTest(){
		//insert specified string at 
                //the offset indicated position.
		System.out.println(sb.insert(3,".javawithease"));
	}
}
 
public class StringBufferInsertExample {
	public static void main(String args[]){
		//creating TestStringBuffer object
		TestStringBuffer obj = new TestStringBuffer();
 
		//method call
		obj.insertTest();
	}
}

Output:

www.javawithease.com

Download this example.
 
Next Topic: replace(int startIndex, int endIndex, String str) StringBuffer method in java.
Previous Topic: append(String str) StringBuffer method in java.

Related Topics:

StringBuffer in java.
append(String str) StringBuffer method in java.
insert(int offset, String str) StringBuffer method in java.
replace(int startIndex, int endIndex, String str) StringBuffer method in java.
delete(int startIndex, int endIndex) StringBuffer method in java.
reverse() StringBuffer method in java.
capacity() StringBuffer method in java.
ensureCapacity(int minCapacity) StringBuffer method in java.
StringTokenizer in java.

 


Comments are closed.