Core Java

OCA Java8 Preparation : StringBuffer & StringBuilder

StringBuilder & StringBuffer are the mutable classes available in java.lang package. They can be thought of an alternative to String when we need to perform a lot of modifications to a String value. Both these classes support same set of operations  but unlike StringBuilder ,the StringBuffer class is thread-safe i.e the operations performed by different threads are synchronised.

An important point to understand here is String class is also thread-safe as it is immutable and so a thread can never change its state.

StringBuffer class is not mentioned in the objectives of OCA Java 8 Exam .So, we will be discussing only StringBuilder class moving forward in the post. However, all you need to understand is that there isn’t much difference among these two available choices. The main difference is thread synchronization available in StringBuffer implementation.

StringBuilder Constructors

StringBuilder class provides below set of constructors to help instantiate its object.

// initial capacity= 16(default) + length(str)
StringBuilder(String str) 
// initial capacity= 16(default) + length(charSeq)
StringBuilder(CharSequence charSeq)
// no content, initial capacity=given capacity(must be >0)
StringBuilder(int capacity)
// no content, initial capacity=16

The default capacity of a StringBuilder object is 16 characters. If any char sequence or String is passed to its constructor , then the initial capacity becomes 16 plus the length of that char sequence or string.

Constructing String from StringBuilder :

The StringBuilder class overrides the toString() method from the Object class. It returns the contents of a StringBuilder object as a String object.

String strValue = strBuilder.toString()

StringBuilder Methods :

Some of the methods in the StringBuilder class are exactly the same as that of String class as they both come from CharSequence interface so I’ll skip the details about those methods. For such methods, I’ll list only the names.

  1. length() : int length()
  2. setLength() : Is used to set the length of StringBuilder object. It might result in the string being truncated or padded with null characters(‘\u0000’).
  3. charAt() : char charAt(int index)
  4. setCharAt() :This method is used to insert a certain character at a given index.It throws IndexOutOfBoundException for invalid indexes.
    void setCharAt(int index, char ch)
  5. deleteCharAt() : deletes the character at a specific position.
    StringBuilder deleteCharAt(int index)
  6. subsequence() : Extracts a character subsequence based on the parameters.
    CharSequence subSequence(int start, int end)

    Note that this method returns a CharSequence and doesn’t modify the existing StringBuilder value.

    StringBuilder sbr =  new StringBuilder("Hello");
    System.out.println(sbr.subSequence(2,3)); //prints l
    System.out.println(sbr); //prints Hello
  7. append() : It is used to append given characters to the end of string builder.
    * Note that it takes an Object parameter
    StringBuilder append(Object obj)
    StringBuilder append(CharSequence chSeq, int start, int end)
    StringBuilder append(char[] chArr, int offset, int length)

    The object parameter is converted to its String equivalent by a method String.valueOf(obj)and then the resulting string is appended to the current value. String.valueOf() method internally invokes the toString() method of that class.

  8. insert() : It is used to insert a given value at a specified position.
    StringBuilder insert(int offset,  Object obj)
    StringBuilder insert(int offset, CharSequence chSeq, int start, int end)

    Above are some of the available constructors of insert() method. offset is used to specify the position at which we need to insert the given value. start and end specifies the range of chSeq to be inserted.

  9. delete() : deletes the substring, which is specified by start index(inclusive) and end index(exclusive).
    StringBuilder delete(int start, int end)
  10. reverse() : reverse the StringBuilder value.You can’t invoke reverse() method to the output of substring() method invoked on a StringBuilder(as the output is a String, not StringBuilder).
    StringBuilder reverse()
  11. capacity() : This method returns the current capacity of StringBuilder class, meaning the number of characters it can accommodate without the need to resize the array.
    int capacity()
  12. ensureCapacity() : It ensures that there is a room for atleast a minCapacity number of characters.It expands it otherwise.
    void ensureCapacity(int minCapacity)
  13. trimToSize() : This method tries to trim the character sequence to to reduce the storage used. It might affect the capacity.
    void trimToSize()
  14. replace() : Unlike for Strings, replace() method in StringBuilder class replaces a sequence of characters identified by their positions with another String.
    StringBuilder replace(int start, int end, String str)

    For instance,

    StringBuilder sbr = new StringBuilder("ABCDE");
    System.out.println(sbr); //prints AB01E

Method Chaining :

If you are following with me through this post, you might have noticed that the methods in the StringBuilder class like insert(),append(),deleteCharAt() etc returns a reference to modified StringBuilder object despite the fact that they all modify the state of the object itself.

For instance, the below code simply works fine.

StringBuilder sbr = new StringBuilder("A");
System.out.println(sbr); //prints AB

Then why do these methods return a StringBuilder reference.The answer to this is that it helps us implement chain of methods.You can refer below example to understand it well.

StringBuilder sbr = new StringBuilder("Hello Tracy");
System.out.println(sbr); //prints "HZlo TracyA"

String vs StringBuilder :

Apart from the fact that StringBuilder is mutable, there are other couple of difference between these two classes that are noteworthy.

  1. Unlike String, StringBuilder class does not implements Comparable interface.Be aware of the use of compareTo() on StringBuilder object as such a code will not compile.
  2. StringBuilder class does not override the equals() & hashcode() methods from the Object class. StringBuilder object can be converted to String in order to obtain the hashCode() value.
  3. There is no implementation of trim() method available in StringBuilder and any attempt to invoke it will make the code compilation fail.


Be the First to comment.

Leave a Comment

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