Difference between String & StringBuffer

Answer Posted / charan

A String is immutable, i.e. when it's created, it can never change.
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 littleStrings along the way.

The maximum length for both is Integer.MAX_VALUE, because they are stored internally as arrays, and Java arrays only have an int for their length pseudo-field.
The performance improvement between Strings and StringBuffers for multiple concatenations is quite significant.

If you run the following test code, you will see the difference. On my ancient laptop with Java 6, I get these results:
Concat with String took: 1781ms
Concat with StringBuffer took: 0ms

Code:

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");
}
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is difference between local variable and global variable?

467


Write a program to check for a prime number in java?

555


Differentiate jar and war files?

586


What are different type of exceptions in java?

542


How do you convert string to int in java?

550






What is a boolean in java?

573


In how many ways we can do exception handling in java?

569


What is the method to declare member of a class static?

532


Can a lock be acquired on a class in java programming?

529


What are JVM.JRE, J2EE, JNI?

682


What is difference between wait and notify in java?

535


why java uses class level type casting ?

2247


What is a condition in java?

529


What are the important methods of java exception class?

567


What is difference between equals and hashcode method?

566