Tuesday, 11 November 2014

StringBuffer vs StringBuilder

To check StringBuffer vs StringBuilder we must check AbstractStringBuffer first coz both StringBuffer and StringBuilder extends AbstractStringBuilder.


AbstractStringBuilder


AbstractStringBuilder has 'char value[]' that is used for holding string in from of char sequence. 'int count' is used for storing number of characters stored.


Important methods in AbstractStringBuilder:

  1. capacity(): Capacity is amount of store available for newly inserted characters

  2.  insert(int, <T>): insert <T> into character sequence at int.

  3. reverse(): Reverse of the character sequence

  4. append(): Append to the character sequence

  5.  toString(): Only abstract method in AbstractStringBuilder


  6. getValue(): This is a final method that returns char value[];




In simple words all operations are done on array of characters which is present in AbstractStringBuilder.

Now StringBuffer vs StringBuilder

  1. StringBuffer and StringBuilder extends AbastractStringBuilder

  2. Both use AbastractStringBuilder for logical operation and has minimal code written in them

  3. Both implements toString() where they create new String and do not share char value[] with String.

  4. Both implements writeObject() &  readObject()


Now the major and important difference is all important methods in StringBuffer are synchronized. Due to non synchronized methonds StringBuilder performs better than StringBuffer.

No comments:

Post a Comment