Monday, 16 December 2013

Unknown

Difference between string and stringbuffer class


String
  • Ikt is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer:
  • A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little Strings along the way.
  • StringBuffer is used to represent characters that can be modified.
  • Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.
Example:

public class Concat
{
    public static String concatWithString()
    {
        String t = "Cat";
        for (int i=0; i<10000; i++)
        {
            t = t + "Dog";
        }
        return t;
    }
    public static String concatWithStringBuffer()
    {
        StringBuffer sb = new StringBuffer("Cat");
        for (int i=0; i<10000; i++)
        {
            sb.append("Dog");
        }
        return sb.toString();
    }
    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        concatWithString();
        System.out.println("Concat with String took: " + (System.currentTimeMillis() - start) + "ms");
        start = System.currentTimeMillis();
        concatWithStringBuffer();
        System.out.println("Concat with StringBuffer took: " + (System.currentTimeMillis() - start) + "ms");
    }
}

Unknown

About Blog No Baap -

Since 2016 BlogNoBaap has been bringing you the very best in all types of web resources. Posted daily, and delivered straight to your inbox each morning.

Subscribe to this Blog via Email :