Saturday 5 November 2016

Java Source World: StringBuffer and StringBuilder in Java

StringBuffer and StringBuilder in Java | Java Source World

                                                               Java Source World                   A Java quick reference blog



StringBuffer and StringBuilder:


                                                Fig: StringBuilder and StringBuffer



StringBuffer


It is mutable in java i.e an existing string buffer itself can be modified to incorporate the changes.
String buffer is synchronized in java. It is direct child of  Object super class.

Syntax:

StringBuffer sb = new StringBuffer("Java Source World");

If we try to assign the string directly it gives us compile time error. 



StringBuffer sbf = "Java Source World";//compiletime error


By default empty string buffer allocates 16 bytes of memory.


If a string buffer is created with some content then string buffer capacity will be existing content plus 16 characters.

If a string buffer is created with size then memory for extra 16 characters will not be provided.





String Builder (Child of String buffer)


String builder is not synchronized. Hence it supports better performance.
It has inherited all the methods of string buffer.



Read Why String is immutable in java?



Differences between StringBuffer and StringBuilder:



String


StringBuffer
String is immutable
StringBuffer is mutable.
String is not synchronized

StringBuffer is Synchronized
Equals() method of String class compares
the contents.
Equals() method of StringBuffer compares the reference(address)
Performance is good when changes are required
Performance is comparatively better when changes are required


Differences between StringBuffer and StringBuilder:



StringBuffer


StringBuilder
StringBuffer  is synchronized

StringBuilder is not Synchronized



How equals() method works in Object, String, StringBuffer, and StringBuilder classes:

Also read Why String is immutable





Object
String
StringBuffer
StringBuilder
Compares address
Compares contents
Compare address
Compare address


In java objects are created in "heap" and local variables are created in "stack".




You may like the fallowing posts:

                                                              Java Source World                   A Java quick reference blog








No comments:

Post a Comment