Posted by: lrrp | January 31, 2015

Difference Between String, StringBuilder, and StringBuffer Classes with Examples

Today we are going to understand the difference between String, StringBuilder, and StringBuffer. As you will find there are minor differences between the above-mentioned classes.

String

String is immutable  ( once created can not be changed )object. The object created as a String is stored in the  Constant String Pool.
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.String  once assigned can not be changed .

String  demo = ” hello ” ;
// The above object is stored in a constant string pool and its value can not be modified.

demo=”Bye”;     //new “Bye” string is created in the constant pool and referenced by the demo variable
// “hello” string still exists in the string constant pool and its value is not overridden but we lost the reference to the  “hello” string

StringBuffer

StringBuffer is mutable means one can change the value of the object. The object created through StringBuffer is stored in the heapStringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized that is StringBuffer is thread-safe.

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread-safe has disadvantages too as the performance of the StringBuffer hits due to thread-safe property. Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to a string by using
toString() method.

StringBuffer demo1 = new StringBuffer(“Hello”) ;
// The above object is stored in a heap and its value can be changed.

demo1=new StringBuffer(“Bye”);
//The Above statement is right as it modifies the value that is allowed in the StringBuffer

StringBuilder

StringBuilder is the same as the StringBuffer, that is it stores the object in a heap and it can also be modified. The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread-safe. 
StringBuilder is fast as it is not thread-safe.

StringBuilder demo2= new StringBuilder(“Hello”);
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder(“Bye”);
// Above statement is right as it modifies the value that is allowed in the StringBuilder

String


Responses

  1. […] Resource: String Vs StringBuffer Vs StringBuilder […]

  2. […] 资源:字符串与字符串缓冲区与字&#x7… […]

  3. Elise Dixon's avatar

    Very creaative post


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories

Design a site like this with WordPress.com
Get started