VOOZH about

URL: https://www.geeksforgeeks.org/java/stringbuffer-insert-java/

⇱ StringBuffer insert() in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

StringBuffer insert() in Java

Last Updated : 5 Dec, 2024

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.


Output
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.

Syntax of StringBuffer.insert() Method

str.insert(int position, data_type value);

Parameters:

  • position: This is the index in string where we need to insert.
  • value: This is the element to be inserted at the position the data type of value can vary.

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.

Example 1: Use with Boolean Input

In this example, we insert a boolean value at a given position in the StringBuffer.


Output
String: geeks for geeks
After insertion: geeks fotruer geeks


Example 2: Use with Character Array Input

In this example, we insert a character array at a given position in the StringBuffer.


Output
String: geeks for geeks
After insertion: geeks foJavar geeks

Example 3: Use with Float Input

In this example, we insert a float value at a given position in the StringBuffer.


Output
String: geeks for geeks
After insertion: geeks fo41.35r geeks

Example 4: Use with Double Input

In this example, we insert a double value into a StringBuffer.


Output
String: geeks for geeks
After insertion: geeks fo41.35r geeks


Example 5: Use with Long Input

In this example, we insert a long value into a StringBuffer.


Output
String: geeks for geeks
After insertion: geeks fo546986r geeks

Example 6: Use with Int Input

In this example, we insert an integer into a StringBuffer.


Output
String: geeks for geeks
After insertion: geeks fo10r geeks


Comment