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.

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.

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.
  5. deleteCharAt() : deletes the character at a specific position.
  6. subsequence() : Extracts a character subsequence based on the parameters.

    Note that this method returns a CharSequence and doesn’t modify the existing StringBuilder value.
  7. append() : It is used to append given characters to the end of string builder.

    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.

    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).
  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).
  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.
  12. ensureCapacity() : It ensures that there is a room for atleast a minCapacity number of characters.It expands it otherwise.
  13. trimToSize() : This method tries to trim the character sequence to to reduce the storage used. It might affect the capacity.
  14. replace() : Unlike for Strings, replace() method in StringBuilder class replaces a sequence of characters identified by their positions with another String.

    For instance,

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.

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.

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 *