Wednesday, 7 December 2011

Difference Between String,StringBuffer and StringBuilder in java


Java's standard way to handle text is to use its String class. Any given String in Java is an immutable object, which means its content cannot be changed. A String has an array of characters. Whenever a String must be manipulated, any changes require the creation of a new String (which involves the creation of a new array of characters, and copying of the original array).For example

String s1=new String(”Hello”);// line 1
s1=s1+”Welcome”;// line 2

First line creates a String object in heap area with content “Hello” and makes s1 to reference this object.Second line creates a new String object in heap with content “Hello Welcome” and makes s1 to reference this new object.Now first string object with content “Hello” have no external reference and hence it is eligible for garbage collection.


I think now you have understood the immutability of String object in Java.Now we can discuss the pros and cons of immutability of String object in java.

Pros:
1)If String is mutable we can't reuse one String object .In case of string pool one string object/literal e.g. "Hello" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected
Consider one example

String s1=”Hello” ;
String s2=”Hello” ;

Here String object with content “Hello” is referenced by 2 reference variables.If String is mutable s1.toUpperCase() will change content of the object itself to “HELLO” and hence it will affect both s1 and s2.

2)Since String is immutable it can safely shared between many threads without any extra synchronization,which is very important for multi-threaded programming and to avoid any synchronization issues in Java.

3)You can securely pass one String object to a function as parameter because the function cant modify the content of the parameter String object.

Cons:

The biggest strength “immutability” is a biggest problem of Java String if not used correctly. Whenever you are modifying one string object e.g appending string,converting string to uppercase ,lowercase ,a new String object will be created and older one is discarded which creates lots of temporary garbage in heap .To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.

StringBuffer
An object of the class StringBuffer can hold a sequence of characters that is mutable and thread-safe. That means, it is very much similar to a String object, but the sequence of characters (length and content) can be changed at any time after initializing the StringBuffer object. However, that should be done using the specific methods provided by the StringBuffer class. There are two principle operations in StringBuffer class. They are provided by append() and insert() methods. The append() method adds the converted string to the end of the existing StringBuffer object, while insert() method will add the input characters to the specified insertion point.
For example:
StringBuffer s=new StringBuffer(“Hello”); //Line 1
s.append(“Hello”);//Line 2

Here line 1 creates a StringBuffer object in heap area with content “Hello”.Line 2 modifies the object created at line 1 without creating a new StringBuffer object.

StringBuilder
StringBuilder class was introduced in JDK 1.5. StringBuilder API is very much similar to StringBuffer API . In fact, StringBuilder class was actually introduced as a replacement for the StringBuffer class for single-thread environment.

Differences between String and StringBuffer in Java

Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. The String class overrides the default equals() method, but StringBuffer and StringBuilder do not override the default equals() method in Object class. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). For example,
 
public class Program {
public static void main(String [] args) {
  String s1 = new String("Hello World");
  String s2 = new String("Hello World");
  System.out.println("s1.equals(s2):" + s1.equals(s2));
  StringBuffer sb1 = new StringBuffer("Hello World");
  StringBuffer sb2 = new StringBuffer("Hello World");
  System.out.println("sb1.equals(sb2):" + sb1.equals(sb2));
  StringBuilder sd1 = new StringBuilder("Hello World");
  StringBuilder sd2 = new StringBuilder("Hello World");
  System.out.println("sd1.equals(sd2):" + sd1.equals(sd2));
}
}

The output is 
s1.equals(s2):true
sb1.equals(sb2):false 
sd1.equals(sd2):false

Difference between StringBuffer and StringBuilder in Java

Although, StringBuilder and StringBuffer classes can be used for mutable sequences of characters in Java, they have a key difference. Unlike StringBuffer class, StringBuilder class is not thread-safe, and provides no synchronization. Therefore, it is recommended that the StringBuilder class should be used in place of StringBuffer class in single-thread applications, because it is claimed that StringBuilder class will be much faster than StringBuffer class (under normal circumstances).


 

3 comments:

  1. In reality StringBuilder is just a copy of StringBuffer without synchronization, if you look code on StringBuilder class you will realize that. by the way here are few more difference between StringBuilder and StringBuffer

    ReplyDelete
  2. Nice Topic and good learning but it will be better to have
    this topic some memory representation.

    ReplyDelete
  3. This is very nice article about Java String vs StringBuffer .
    thanks for this nice post.

    ReplyDelete