Saturday, January 12, 2013

String, String Builder, String Buffer - what, why, when

One of the widely used java class is "String". It comes under “java.lang” package which is imported by default. Yes, by default. You will learn it more under topic "Imports and Packages". As of now, you should understand that java compiler automatically imports "java.lang" package which contains essential classes which are frequently used.

String are the stream of characters and each character is a 16-bit Unicode character, and since its 16-bits,international set of characters are easily represented in Unicode.
In java Strings are nothing but Objects. Just like any other object, you can create instance of String object by "new" keyword. Something like:
                String str = new String ();
This line of code creates a new object of class String, and assigns it to a reference variable s. Let us give 'str' a value:
                str = "knowledge base";
There are zillions of String constructors available. You can also use more efficient shortcut: 
               String str = new String ("knowledge base");
                              OR even
                String str = "knowledge base";
There are some subtle differences between these constructors but what they have in common is they all will create a new object of class String.
If you need to assign a new reference variable to “knowledge base”, you can simply do:
              String anotherStr = str;   //this will refer to same string referred to by “str”.
            

String object behaves like any other object except for the fact the String in java is “immutable”. Yes, string object once created, can never be changed. Once you assign a value, that value can never change. We’ll explore more about string immutability in upcoming topics in “Knowledge Base”.

StringBuilder & StringBuffer Introduction
Now, since string value cannot be changed, what if you need to do lots of modifications in a string? Well, then comes the use of two classes provided by java StringBuffer & StringBuilder.
StringBuffer is old class while StringBuilder is new and was introduced in Java 1.5. Both these classes also come under “java.lang” package. While String class is immutable, StringBuffer and StringBuilder are mutable and objects of StringBuilder and StringBuffer can be modified over and over again.

The following simple program will help you understand the change in values using StringBuffer and StringBuilder objects.
/**
 * 
 * @author knowledge base
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        String str = "Knowledge";
        str.concat("Base");
        System.out.println("string is immutable: "+str);
        
        StringBuffer s = new StringBuffer("Knowledge");
        s.append(" Base");
        System.out.println("string buffer is mutable: "+s);
        
        StringBuilder sb = new StringBuilder("knowledge");
        sb.append(" base");
        System.out.println("string builder is also mutable: "+sb);
        
    }

}

And the output is:

Difference between StringBuffer & StringBuilder

StringBuffer and StringBuilder classes are almost same in the APIs they possess but differ mainly in one thing and i.e. “thread-safety”.
  1. StringBuffer is very good with mutable string but all its public methods are “synchronized” which  makes it thread safe.
  2. Due to synchronization, StringBuffer is slow as compared to StringBuffer which is non-synchronized and hence much faster than StringBuffer.
  3. Java Developers recommends use of StringBuilder wherever possible as it runs faster.
Rest everything said for StringBuffer holds true for StringBuilder and vice-versa. And hence to sum up the topic, below note is important:
          Use String if you require “immutability”, StringBuffer if you require “frequent modifications + thread-safety” and StringBuilder if you need  “mutability without thread-safety”.



Cheers!

On the bottom of my Pocket....