Friday, January 1, 2016

Difference Between StringBuffer and StringBuilder in Java

This is Most Important Question when you face Technical Round and Written Test.So I am going to discuss difference between StringBuffer and StringBuilder. I had alreadygiven best article about  String in java.Here String and StringBuffer and StringBuilder all are classes in Java.


Let me Define String,StringBuffer and StringBuilder

String:  String is a group of characters or Sequence of characters and it Immutable class in Java.
StringBuffer:   It is also group of characters but it is Mutable class in java
StringBuilder: It is also group of characters and it is also Mutable class in java

Now Let us See The Differences Between the String, StringBuffer and StringBuilder in Java

Difference between String and StringBuffer:

The main difference between String and StrigBuffer that String is Immutable while  StringBuffer is mutable Object in java.Immutable means once we created can not be changed that is the object created for String then it will stored in String Constant Pool(SCP) whereas Mutable means One change the value of the object here the when we create object for StringBuffer then it stores in the heap memory.The java authors makes your job very easy because you can convert StringBuffer into String by using a method toString().

Difference between StringBuffer and StringBuilder in Java

StringBuffer:  StringBuffer is mutable that means one can change the value of the object.StringBuffer value can be changed that means you assign new value.When we create object for StringBuffer it stores into the Heap Memory. StringBuffer is Synchornized that StringBuffer is ThreadSafe. Here ThreadSafe means it does not allows two threads to simultaneously not access on the same method. It can access the method one thread at a time. Therefore the performance wise it is slow. But java provides in JDK5 another feature called as StringBuilder but it is not Synchronized.

StringBuilder: StringBuilder is also mutable that means one can change the value of the object.It is same like as StringBuffer.The main difference between StringBuffer and StringBuilder is  StringBuilder is not Synchronized that means it is not Thread-safe which makes StringBuilder faster than StringBuffer.


When do we Use String, StringBuffer and StringBuilder in java?

Use String when you require Immutability. 
Use StringBuffer when you require mutability and Thread-safe
Use StringBuilder when you require mutability and not Thread-safe






No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...