![]() |
VOOZH | about |
The StringBuffer.insert() method in Java allows us to insert a string representation of a given data type at a specified position in a StringBuffer. This method is useful when we need to modify a string at specific positions without creating a new string each time by making it more efficient than concatenation.
Example: In the following example, we will insert a character into a StringBuffer at a specified position.
String: geeks for geeks After insertion: geEeks for geeks
Explanation: In this example, we insert the character "E" at index 2 in the StringBuffer. The original string "geeks for geeks" becomes "geEeks for geeks" after the insertion.
str.insert(int position, data_type value);
Parameters:
Return Type: This method returns a reference to the StringBuffer object.
Exception: The position must be greater than or equal to 0, and less than or equal to the length of the string.
In this example, we insert a boolean value at a given position in the StringBuffer.
String: geeks for geeks After insertion: geeks fotruer geeks
In this example, we insert a character array at a given position in the StringBuffer.
String: geeks for geeks After insertion: geeks foJavar geeks
In this example, we insert a float value at a given position in the StringBuffer.
String: geeks for geeks After insertion: geeks fo41.35r geeks
In this example, we insert a double value into a StringBuffer.
String: geeks for geeks After insertion: geeks fo41.35r geeks
In this example, we insert a long value into a StringBuffer.
String: geeks for geeks After insertion: geeks fo546986r geeks
In this example, we insert an integer into a StringBuffer.
String: geeks for geeks After insertion: geeks fo10r geeks