1. StringBuilder Class in Java
The StringBuilder class is used to create and modify mutable strings in Java.
Unlike the String class, StringBuilder objects can be changed without creating new objects repeatedly.
2. Why StringBuilder is Used
StringBuilder improves performance when frequent string modifications are required.
- a. Reduces unnecessary object creation
- b. Improves memory efficiency
- c. Faster than String concatenation
- d. Useful for loops and dynamic text
- e. Supports multiple modification methods
3. Where StringBuilder is Used
StringBuilder is commonly used in applications where text changes frequently.
- a. Report generation
- b. Dynamic message creation
- c. File processing
- d. Loop-based string operations
- e. JSON and XML generation
- f. Data formatting systems
4. Creating a StringBuilder Object
A StringBuilder object can be created using different constructors.
4.1 Empty StringBuilder
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
System.out.println(builder);
}
}
This creates an empty StringBuilder object.
4.2 StringBuilder with Initial Text
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
System.out.println(builder);
}
}
The object is initialized with the text Java.
4.3 StringBuilder with Capacity
Capacity means the amount of character storage available before resizing happens.
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder(50);
System.out.println(builder.capacity());
}
}
The output shows the initial capacity value.
StringBuilder automatically increases capacity when needed.
5. append() Method
The append() method adds data at the end of the existing text.
5.1 Basic append() Example
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.append(" Programming");
System.out.println(builder);
}
}
The text Programming is added at the end of the existing text.
5.2 Appending Multiple Values
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("Age: ");
builder.append(25);
System.out.println(builder);
}
}
append() can add strings, integers, booleans, and other data types.
6. insert() Method
The insert() method inserts text at a specific position.
6.1 Example of insert()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.insert(4, " Language");
System.out.println(builder);
}
}
The text Language is inserted starting from index 4.
Providing an invalid index in insert() causes StringIndexOutOfBoundsException.
7. delete() Method
The delete() method removes characters from a specified range.
7.1 Example of delete()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java Programming");
builder.delete(4, 16);
System.out.println(builder);
}
}
Characters between index 4 and 15 are removed.
8. deleteCharAt() Method
The deleteCharAt() method removes a single character from a specific index.
8.1 Example of deleteCharAt()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.deleteCharAt(1);
System.out.println(builder);
}
}
The character at index 1 is removed from the text.
9. replace() Method
The replace() method replaces characters between specific indexes.
9.1 Example of replace()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java Language");
builder.replace(5, 13, "Programming");
System.out.println(builder);
}
}
The word Language is replaced with Programming.
The ending index is excluded during replacement.
10. reverse() Method
The reverse() method reverses the character sequence.
10.1 Example of reverse()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.reverse();
System.out.println(builder);
}
}
The output becomes avaJ.
11. length() Method
The length() method returns the total number of characters currently stored.
11.1 Example of length()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Programming");
System.out.println(builder.length());
}
}
The output shows the total number of characters.
12. capacity() Method
The capacity() method returns the current storage capacity of the object.
12.1 Example of capacity()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
System.out.println(builder.capacity());
}
}
The default capacity of an empty StringBuilder is 16.
12.2 Capacity Expansion
When capacity becomes full, Java automatically increases it.
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("abcdefghijklmnopqrstuvwxyz");
System.out.println(builder.capacity());
}
}
The capacity increases automatically when more space is required.
Automatic resizing improves flexibility but may involve additional memory allocation.
13. setCharAt() Method
The setCharAt() method changes a character at a specific index.
13.1 Example of setCharAt()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.setCharAt(0, 'K');
System.out.println(builder);
}
}
The character J is replaced with K.
14. toString() Method
The toString() method converts a StringBuilder object into a String object.
14.1 Example of toString()
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
String result = builder.toString();
System.out.println(result);
}
}
The mutable StringBuilder data is converted into an immutable String.
15. Internal Working of StringBuilder
Internally, StringBuilder uses a resizable character array.
15.1 Mutable Character Storage
Unlike String objects, StringBuilder directly modifies its internal array instead of creating new objects repeatedly.
StringBuilder builder = new StringBuilder("Java");
builder.append(" Programming");
The existing object is modified internally instead of creating a completely new object.
15.2 Capacity Growth Formula
When capacity becomes full, Java increases it using an internal formula.
newCapacity = (oldCapacity * 2) + 2
This resizing strategy helps reduce frequent memory allocations.
16. Performance Benefits of StringBuilder
StringBuilder is much faster than normal String concatenation during repeated modifications.
16.1 Problem with String Concatenation
public class Main {
public static void main(String[] args) {
String text = "";
for(int i = 1; i <= 5; i++) {
text = text + i;
}
System.out.println(text);
}
}
This approach creates multiple temporary String objects.
16.2 Better Solution Using StringBuilder
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
for(int i = 1; i <= 5; i++) {
builder.append(i);
}
System.out.println(builder);
}
}
This approach modifies the same object repeatedly and improves performance.
17. Thread Safety and StringBuilder
StringBuilder is not thread-safe.
If multiple threads modify the same object simultaneously, unexpected results may occur.
17.1 Why StringBuilder is Faster
StringBuilder does not use synchronization.
Because synchronization is avoided, operations become faster.
Use StringBuilder mainly in single-threaded environments.
18. Difference Between String and StringBuilder
| Feature | String | StringBuilder |
| Mutability | Immutable | Mutable |
| Performance | Slower for modifications | Faster for modifications |
| Memory Usage | Creates new objects | Modifies same object |
| Thread Safety | Safe because immutable | Not thread-safe |
| Use Case | Fixed text | Frequently changing text |
19. Difference Between StringBuilder and StringBuffer
Both classes are mutable, but their thread safety behavior is different.
| Feature | StringBuilder | StringBuffer |
| Thread Safety | No | Yes |
| Performance | Faster | Slower |
| Synchronization | Not synchronized | Synchronized |
Use StringBuilder when thread safety is not required.
20. Common Beginner Mistakes
20.1 Confusing Capacity and Length
Length means current character count, while capacity means available storage space.
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
System.out.println(builder.length());
System.out.println(builder.capacity());
}
}
The outputs are different because both methods represent different concepts.
20.2 Using Invalid Indexes
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.deleteCharAt(10);
}
}
This code throws StringIndexOutOfBoundsException because the index does not exist.
20.3 Forgetting to Convert into String
Sometimes a String object is required instead of a StringBuilder object.
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
String result = builder.toString();
System.out.println(result);
}
}
toString() converts mutable text into an immutable String object.
21. Edge Cases in StringBuilder
21.1 Reversing Empty Text
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.reverse();
System.out.println(builder);
}
}
No error occurs because reversing empty text is valid.
21.2 Large Dynamic Text Creation
StringBuilder performs efficiently even when handling very large text data.
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
for(int i = 1; i <= 1000; i++) {
builder.append(i);
}
System.out.println(builder.length());
}
}
The object grows dynamically as more data is added.
22. Important Points to Remember
- a. StringBuilder is mutable
- b. It improves performance during repeated modifications
- c. append() adds data at the end
- d. insert() adds data at a specific position
- e. reverse() reverses characters
- f. capacity() and length() are different
- g. StringBuilder is not thread-safe
- h. toString() converts it into a String
The Java StringBuilder class is an efficient solution for handling frequently changing text data. Because it modifies the same object instead of creating multiple temporary objects, it provides better memory usage and faster performance compared to normal String concatenation.
