StringBuffer in Java

Filed Under: Java

StringBuffer in java is used to create modifiable String objects. This means that we can use StringBuffer to append, reverse, replace, concatenate and manipulate Strings or sequence of characters. Corresponding methods under StringBuffer class are respectively created to adhere to these functions.

In Java, Strings are known to be immutable or un-editable, unless overwritten upon. This is where StringBuffer class comes into picture, where it can accommodate character sequences and still enable a mutable feature.

StringBuffer in Java

Some important points about StringBuffer in java are:

  • StringBuffer is much alike the String class, but with mutability features.
  • Unlike Strings where the length and memory allocation are final, StringBuffer has existing methods to modify these properties.
  • StringBuffer is thread safe, most of it’s methods are synchronized. So StringBuffer object can’t be accessed or used by multiple threads at the same time.
  • java.lang.StringBuffer extends AbstractStringBuilder abstract class.
  • StringBuffer inherits clone(), equals(), finalize(), getClass(), hashCode(), notify() and notifyAll() methods from java.lang.Object super class.
  • StringBuffer implements CharSequence, Appendable and Serializable interfaces.
  • StringBuffer capacity() method can be used to retrieve the memory available for new character sequences to be added, beyond which the allocation will occur.
  • Compared to StringBuilder Class, StringBuffer operates slower due to synchronization.

Java StringBuffer class features the flexibility of character sequence memory allocation. This means we can modify the given String using StringBuffer class. What makes this possible is that StringBuffer class reserves contingent memory for future modification.

StringBuffer Class Diagram

Below image illustrates the interfaces implemented by StringBuffer class. Notice that StringBuffer extends AbstractStringBuilder class that was introduced in Java 1.5 when StringBuilder was also introduced.

StringBuffer in Java

StringBuffer Constructors

  1. StringBuffer(): Creates a StringBuffer with empty content and 16 reserved characters by default.
    
    StringBuffer sb = new StringBuffer();
    
  2. StringBuffer(int sizeOfBuffer): Creates a StringBuffer with the passed argument as the size of the empty buffer.
    
    StringBuffer sb = new StringBuffer(20);
    
  3. StringBuffer(String string): Creates a StringBuffer with the passed String as the initial content of the buffer. 16 contingent memory characters are pre-allocated, not including the buffer, for modification purposes.
    
    StringBuffer sb = new StringBuffer("Hello World!");
    

StringBuffer Methods

  1. length(): Returns the StringBuffer object’s length.
  2. capacity(): Returns the capacity of the StringBuffer object.
  3. 
    package com.journaldev.java;
    
    public class StringBufferExample {
    
    	public static void main(String[] args) {
    		StringBuffer sb = new StringBuffer("Hello");
    		int sbLength = sb.length();
    		int sbCapacity = sb.capacity();
    		System.out.println("String Length of " + sb + " is " + sbLength);
    		System.out.println("Capacity of " + sb + " is " + sbCapacity);
    	}
    
    }
    

    Output produced by above StringBuffer example program:

    
    String Length of Hello is 5
    Capacity of Hello is 21
    
  4. append(): appends the specified argument string representation at the end of the existing String Buffer. This method is overloaded for all the primitive data types and Object.
  5. 
    StringBuffer sb = new StringBuffer("Hello ");
    
    sb.append("World ");
    
    sb.append(2017);
    
    System.out.println(sb);
    

    Output: Hello World 2017

  6. insert(): insert() method takes two parameters – the index integer value to insert a value and the value to be inserted. The index tells StringBuffer where to insert the passed character sequence. Again this method is overloaded to work with primitive data types and Objects.
  7. 
    StringBuffer sb = new StringBuffer("HelloWorld ");
    
    sb.insert(5, " ");
    
    sb.insert(sb.length(), 2017);
    
    System.out.println(sb);
    

    Output: Hello World 2017

  8. reverse(): Reverses the existing String or character sequence content in the buffer and returns it. The object must have an existing content or else a NullPointerException is thrown.
  9. 
    StringBuffer sb = new StringBuffer("Hello World");
    
    System.out.println(sb.reverse());
    

    Output: dlroW olleH

  10. delete(int startIndex, int endIndex): accepts two integer arguments. The former serves as the starting delete index and latter as the ending delete index. Therefore the character sequence between startIndex and endIndex–1 are deleted. The remaining String content in the buffer is returned.
  11. 
    StringBuffer sb = new StringBuffer("Hello World");
    
    System.out.println(sb.delete(5,11)); //prints Hello
    
  12. deleteCharAt(int index): deletes single character within the String inside the buffer. The location of the deleted character is determined by the passed integer index. The remaining String content in the buffer is returned.
  13. 
    StringBuffer sb = new StringBuffer("Hello World!");
    
    System.out.println(sb.deleteCharAt(11)); //prints "Hello World"
    
  14. replace(int startIndex, int endIndex, String str): Accepts three arguments: first two being the starting and ending index of the existing String Buffer. Therefore the character sequence between startIndex and endIndex–1 are removed. Then the String passed as third argument is inserted at startIndex.
  15. 
    StringBuffer sb = new StringBuffer("Hello World!");
    
    System.out.println(sb.replace(6,11,"Earth")); //prints "Hello Earth!"
    

That’s all for StringBuffer in Java. Most of the time we don’t need to use StringBuffer because String is immutable and we can use StringBuilder in single threaded environments. You should use StringBuffer only when multiple threads are modifying it’s contents.

Reference: API Doc

Comments

  1. Pradeepa says:

    Ur tutorial is awesome u describe All methods simple than In my text thanks ur tutorial help me in my seminars

  2. Yeremia Maroutian says:

    Hey, Pankaj. I like your tutorial and currently I am reading it. If you have anything on core java API’s, please send them to me.
    Thanks. Regards.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages