String Buffer in Java


String Buffer class


Key Points:

  • used to created mutable (modifiable) string.
  • Mutable: Which can be changed.
  • is thread-safe i.e. multiple threads cannot access it simultaneously.

Methods:

  • public synchronized StringBuffer append(String s)
  • public synchronized StringBuffer insert(int offset, String s)
  • public synchronized StringBuffer replace(int startIndex, int endIndex, String str)
  • public synchronized StringBuffer delete(int startIndex, int endIndex)
  • public synchronized StringBuffer reverse()
  • public int capacity()
  • public void ensureCapacity(int minimumCapacity)
  • public char charAt(int index)
  • public int length()
  • public String substring(int beginIndex)
  • public String substring(int beginIndex, int endIndex)

Example Showing difference between String and String Buffer implementation:

class Test
{
    public static void main(String args[])
	{
        // Example with String
        String str = "study";
        String newStr = str.concat(" tonight"); // Concatenation creates a new string
        System.out.println("Original String: " + str); // Output: study
        System.out.println("New String: " + newStr); // Output: study tonight
 
        // Example with StringBuffer
        StringBuffer strB = new StringBuffer("study");
        strB.append(" tonight"); // StringBuffer appends directly to the existing object
        System.out.println("StringBuffer: " + strB); // Output: study tonight
    }
}

Result:

Original String: study
New String: study tonight
StringBuffer: study tonight
  • For String, when you use the concat() method, it creates a new string with the concatenated value. The original string remains unchanged (str), and the modified string is stored in newStr.
  • For StringBuffer, the append() method directly modifies the existing StringBuffer object by adding the specified string (" tonight" in this case) to the end.

This illustrates a fundamental difference between String (immutable) and StringBuffer (mutable) in Java. With String, operations like concatenation generate new string objects, while StringBuffer allows direct modification of the string content without creating new objects, making it more efficient for extensive string manipulation.

Basic Programs