CodesJava

Easy learning with example program codes

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


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

Syntax:

public StringBuilder 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:

StringBuilderInsertExample.java

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

Output:

www.codesjava.com

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

 

Please follow and like us:
Posted in Java   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki