In this guide, you will learn about the StringBuilder insert() method in Java programming and how to use it with an example.
1. StringBuilder insert() Method Overview
Definition:
The insert() method in the StringBuilder class is used to insert data into the current sequence at the specified position.
Syntax:
stringBuilder.insert(index, data)
Parameters:
- index: The position at which to insert data.
- data: The data to be inserted.
Key Points:
- The method is overloaded to accept various data types, including char, CharSequence, boolean, int, long, float, double, etc.
- The index refers to the position in the current character sequence where the new data will begin.
- If the index is equal to the length of the current sequence, the data is appended at the end.
- Throws StringIndexOutOfBoundsException if the index is negative or greater than the length of this sequence.
- Inserting a null reference using any of the insert() methods will result in the four characters "null" being inserted.
2. StringBuilder insert() Method Example
public class StringBuilderInsertExample {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Hello World");
// Inserting a string at position 5
builder.insert(5, ", dear");
System.out.println(builder); // Outputs: Hello, dear World
// Inserting a character array
char[] charArray = {'!', '!', ' '};
builder.insert(12, charArray);
System.out.println(builder); // Outputs: Hello, dear!! World
// Inserting a boolean value at the end
builder.insert(builder.length(), false);
System.out.println(builder); // Outputs: Hello, dear!! Worldfalse
}
}
Output:
Hello, dear World Hello, dear!! World Hello, dear!! Worldfalse
Explanation:
In this example:
1. We initiate with a StringBuilder object containing the string "Hello World".
2. We use the insert() method to insert the string ", dear" at the 5th position.
3. We insert a character array charArray at the 12th position.
4. Finally, we demonstrate that the insert() method can accept various data types by inserting a boolean value at the end.
The insert() method is versatile due to its multiple overloads that allow for inserting different data types. It provides flexibility and efficiency when adding data to a StringBuilder object at specified positions, eliminating the need for string concatenations.
Comments
Post a Comment
Leave Comment