Sunday, October 26, 2014

String, StringBuffer and StringBuilder

With respect to C or C++ in java String handling is different. Java provides String class to represent Strings. For better memory utilization java treats String as constant and their value can't be changed.
This behavior is popularly known as immutable.The idea is if some one write
String hello = "Hello"; 
String greetings = "Hello";
Internally both refer to same object. In JVM memory area there is a dedicated memory for these String literals, known as String pool.
So in our example hello == greetings will return true.
But if someone write
String str = new String("Hello");
It will create a new object, it won't point to same literal available in string pool.
So hello == str will return false. 
Another advantage of java String is we can use + for concatenation.

String greetMe = hello + "Java";

We can concatenate diffrent type of object other than String with String too. The typecast is automatic.String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.
As we learned String objects are immutable means the values cannot be altered. So strings are always thread safe. Any operation such as hello.toLowerCase() will result another object. For extensive String manipulation java provides two other classes StringBuffer and StringBuilder. These classes gives us a way to manipulate String efficiently. The only difference is StringBuffer is thread safe while StringBuilder is not. So by design StringBuilder is faster than StringBuffer.

So when to use what

String is used to handle multiple literal, it gives you optimum way to handle duplicate literal for better memory utilization.

StringBuffer is natural choice if we need to do a lots of String manipulation in a thread safe way. If synchronization is not the issue StringBuilder should be used since its faster than StringBuffer.

Have fun with your Strings  ;)