Home »
Java programming language
Java StringBuffer insert(int offset , String s) method with Example
Java StringBuffer insert(int offset , String s) method: Here, we are going to learn about the insert(int offset , String s) method of StringBuffer class with its syntax and example.
Submitted by Preeti Jain, on June 29, 2019
StringBuffer Class insert(int offset , String s)
- This method is available in package java.lang.StringBuffer.insert(int offset, String s).
- This method is used to insert the string representation with the given object at the specified position.
-
This method is overridable so it is available in different-2 forms like:
- StringBuffer insert(int offset , boolean b)
- StringBuffer insert(int offset , char c)
- StringBuffer insert(int offset , char[] c) etc
Syntax:
StringBuffer insert(int offset , String s){
}
Parameter(s):
We can pass two or three objects according to our need as a parameter in the method and that object will insert in a sequence at the specified position.
Return value:
The return type of this method is StringBuffer that means this method returns a reference to this object.
Java program to demonstrate example of insert() method
import java.lang.StringBuffer;
public class StringBufferClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java is a programming language : ");
// use insert(int offset ,Boolean b) it will insert the Boolean parameter
// at index 33 as string to the StringBuffer
sb.insert(33, true);
// Display result after inserting
System.out.println("The result will be after inserting Boolean object to the StringBuffer is :" + sb.toString());
sb = new StringBuffer("Version of Java is : ");
// use insert(int offset , int i) it will insert the Integer parameter
// at index 21 as string to the StringBuffer
sb.insert(21, 8);
// Display result after inserting
System.out.println("The result will be after inserting Integer object to the StringBuffer is :" + sb.toString());
}
}
Output
D:\Programs>javac StringBufferClass.java
D:\Programs>java StringBufferClass
The result will be after inserting Boolean object to the StringBuffer is :Java is a programming language : true
The result will be after inserting Integer object to the StringBuffer is :Version of Java is : 8