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
we have syntax like for(int var : arrayName) this syntax is to find whether a number is in the array or not.but i want to know how to find that number's location.
Can an interface have a class?
Is sizeof a preprocessor?
What sorting algorithm does javascript use?
What are the various access specifiers in java?
What are the changes in java.io in java 8 ?
What is hash in java?
What is the difference between stored procedure & function?
When throw keyword is used?
Why do we need data serialization?
What are the differences between stringbuffer and stringbuilder?
What purpose do the keywords final, finally, and finalize fulfill?
What is the purpose of using javap?
How to sort array of 0 and 1 in java?
Is double bigger than float?