Java StringBuilder
StringBuilder lets us build text by changing one editable sequence of characters. Unlike a String, its contents can change after the object is created. It is useful when a result is assembled in several steps, such as a name list or a short report.
Create and Append Text
public class HelloWorld {
public static void main(String[] args) {
StringBuilder message = new StringBuilder("Hello");
message.append(", ");
message.append("Mira");
System.out.println(message);
}
}Output:
Hello, Miraappend() adds text to the end. It changes message itself. We do not need to assign the result back for that change to remain in the builder.
Add Text at a Position
public class HelloWorld {
public static void main(String[] args) {
StringBuilder name = new StringBuilder("Mira Rao");
name.insert(5, "K. ");
System.out.println(name);
}
}Output:
Mira K. RaoPositions start at zero. Here index 5 is just before Rao. Inserting beyond the valid range causes an index error.
Replace and Delete a Range
public class HelloWorld {
public static void main(String[] args) {
StringBuilder label = new StringBuilder("Room 12");
label.replace(5, 7, "24");
System.out.println(label);
label.delete(4, 7);
System.out.println(label);
}
}Output:
Room 24
RoomThe starting index is included and the ending index is excluded. replace() puts new text in that range. delete() removes the range without adding replacement text.
Read and Change One Character
public class HelloWorld {
public static void main(String[] args) {
StringBuilder word = new StringBuilder("cat");
System.out.println(word.charAt(0));
word.setCharAt(0, 'b');
System.out.println(word);
}
}Output:
c
batThese indexes use UTF-16 code units, like String indexes. A character outside the basic multilingual plane uses two code units, so a user-visible character is not always one index position.
Build a List without a Trailing Separator
public class HelloWorld {
public static void main(String[] args) {
String[] names = {"Mira", "Ravi", "Neha"};
StringBuilder result = new StringBuilder();
for (String name : names) {
if (result.length() > 0) {
result.append(", ");
}
result.append(name);
}
System.out.println(result);
}
}Output:
Mira, Ravi, NehaThe separator is added before every name except the first. This avoids deleting an extra separator at the end. For a simple joining task, String.join() is another option; this example shows how a builder helps when formatting has several steps.
Convert the Result to String
Call toString() when another API needs a String. The returned String is a snapshot: later edits to the builder do not change that String.
public class HelloWorld {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Ready");
String saved = builder.toString();
builder.append(" now");
System.out.println(saved);
System.out.println(builder);
}
}Output:
Ready
Ready nowLength and Capacity
length() counts the code units currently stored. capacity() describes the storage the builder has available before it needs to grow. These numbers are not interchangeable. A larger capacity does not mean the text already contains that many characters.
Reverse Text
reverse() changes the order of the sequence in the builder. It handles existing surrogate pairs specially, but reversing code units is not a general solution for reversing every kind of user-visible Unicode text. Combining marks and multi-code-point symbols need additional care.
StringBuilder and Threads
StringBuilder does not synchronize its operations. Keep it local to one task or coordinate shared access explicitly. StringBuffer provides synchronized operations, but a multi-step shared update may still need one lock around the whole sequence.
Compare Text Contents
StringBuilder does not override equals() to compare text contents. For ordinary content comparison, convert the result to String and use String.equals(). Do not assume two separate builders are equal just because printing them shows the same text.
Common Methods
| Method | Use |
|---|---|
| append() | Add text at the end |
| insert() | Add text at an index |
| delete() | Remove a range |
| replace() | Replace a range |
| charAt() | Read one UTF-16 code unit |
| setCharAt() | Change one UTF-16 code unit |
| length() | Read the current text length |
| capacity() | Read the current storage capacity |
| reverse() | Reverse the builder's sequence |
| toString() | Create the result as a String |
Easy Way to Remember
Use String for the finished text. Use a local StringBuilder when building that text through repeated edits. See StringBuffer for the synchronized alternative.
See you in next page....🙂