Java From Beginner To Advanced

0% completed

Previous
Next
StringBuilder and StringBuffer classes

While the String class in Java is immutable, there are scenarios where you need to perform frequent modifications to strings, such as concatenation, insertion, or deletion of characters. In such cases, using mutable classes like StringBuilder and StringBuffer is more efficient. These classes provide a mutable sequence of characters, allowing you to modify strings without creating new objects each time.

What Are StringBuilder and StringBuffer?

  • StringBuilder and StringBuffer are classes in Java that provide mutable sequences of characters.
  • Mutability: Unlike String, these classes allow you to modify the contents without creating new objects.
  • Use Cases: Ideal for scenarios involving frequent string modifications, such as building dynamic content, processing large amounts of text, or performing multiple concatenations.

Key Differences

FeatureStringBuilderStringBuffer
Thread SafetyNot synchronized (Not thread-safe)Synchronized (Thread-safe)
PerformanceFaster in single-threaded environmentsSlower due to synchronization overhead
Use CasePreferred when thread safety is not a concernPreferred in multi-threaded environments

Syntax and Initialization

StringBuilder

StringBuilder sb = new StringBuilder();
  • Default Constructor: Initializes an empty StringBuilder with an initial capacity of 16 characters.
  • Parameterized Constructor: You can specify the initial capacity or initialize with a string.
StringBuilder sb1 = new StringBuilder(50); // Initial capacity of 50 StringBuilder sb2 = new StringBuilder("Hello"); // Initializes with "Hello"

StringBuffer

StringBuffer sb = new StringBuffer();
  • Default Constructor: Initializes an empty StringBuffer with an initial capacity of 16 characters.
  • Parameterized Constructor: Similar to StringBuilder, you can specify the initial capacity or initialize with a string.
StringBuffer sb1 = new StringBuffer(50); // Initial capacity of 50 StringBuffer sb2 = new StringBuffer("Hello"); // Initializes with "Hello"

Examples

Example 1: Using StringBuilder to Build a String

Below is an example that demonstrates how to use the StringBuilder class to efficiently build and modify a string.

Java
Java

. . . .

Explanation:

  • Initialization: A StringBuilder object sb is created with the initial content "Hello".

  • Append: The append() method adds ", World!" to the end, resulting in "Hello, World!".

  • Insert: The insert() method adds " Java" at index 5, changing the string to "Hello Java, World!".

  • Delete: The delete() method removes characters from index 5 to 10, reverting the string back to "Hello, World!".

  • Reverse: The reverse() method reverses the entire string, resulting in "!dlroW ,olleH".

Example 2: Comparing StringBuilder and StringBuffer

This example highlights the differences between StringBuilder and StringBuffer in terms of thread safety and performance.

Java
Java

. . . .

Explanation:

  • Both StringBuilder and StringBuffer are used to append " Programming" to the initial string "Java".
  • The output for both is identical: "Java Programming".
  • The key difference lies in their synchronization:
    • StringBuilder: Not synchronized, making it faster in single-threaded scenarios.

    • StringBuffer: Synchronized, ensuring thread safety in multi-threaded environments.

Common Pre-defined Methods in StringBuilder and StringBuffer Classes

Both StringBuilder and StringBuffer classes offer a variety of methods to manipulate strings efficiently. Below is a table summarizing some of the most frequently used methods:

MethodDescriptionExample Usage
append(String str)Adds the specified string to the end of the current sequence.sb.append(" World") results in "Hello World"
insert(int offset, String str)Inserts the specified string at the given offset.sb.insert(5, " Java") results in "Hello Java World"
delete(int start, int end)Removes characters from the start index (inclusive) to the end index (exclusive).sb.delete(5, 10) removes characters from index 5 to 9
reverse()Reverses the sequence of characters in the current sequence.sb.reverse() reverses "Hello" to "olleH"
toString()Converts the StringBuilder or StringBuffer object to a String.sb.toString() converts the mutable sequence to a String
capacity()Returns the current capacity of the buffer.sb.capacity() might return 16
length()Returns the number of characters in the sequence.sb.length() returns the current length
setLength(int newLength)Sets the length of the character sequence.sb.setLength(10) truncates or pads the sequence
substring(int start, int end)Returns a new string that is a substring of the current sequence.sb.substring(0, 5) extracts the first five characters
charAt(int index)Returns the character at the specified index.sb.charAt(0) returns the first character

Understanding and utilizing the StringBuilder and StringBuffer classes in Java can significantly enhance the efficiency and performance of your applications, especially when dealing with extensive string manipulations. While StringBuilder is ideal for single-threaded environments due to its speed, StringBuffer is suitable for multi-threaded contexts where thread safety is paramount. By mastering these classes and their methods, you can write more optimized and maintainable Java code.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next