Saturday, October 12, 2013

Concepts on String,StringBuffer,StringBuilder and String Pool ?

String:
-----------
String is immutable object that means the string content in the String object can't be modified....
String s = "anil";
s = s+"kumar";
But beginners may think that... String s is modified... But what really happens is
original String s doesn't get modified... A new String will be created with "anil" and "kumar"
and the original reference s will be set to new object.Only reference variable is getting modified
but not the contents in the original object.
So the drawback is many intermediate objects get created and it will be a problem if you are doing
multiple concatenations.
 
 String Buffer:
------------------------
When you are doing multiple concatenations use StringBuffer instead of String.
 StringBuffer is synchronized.
StringBuilder:StringBuilder is same as... StringBuffer.Difference is StringBuilder is not 
synchronized.So performance will be more than StringBuffer.But you have to be careful
while using StringBuilder in multithreaded programmes.
 
 
What is string pool ?
------------------------

When you say new String("Anil");

It always creates an object with content String.

Suppose... if you create new String("Anil") in a for loop
with 1000 iterations.. it will create 1000 string objects.

----------------------------------------------------------------

Above thing is waste of memory.
So java people decided to create a pool of string objects.

So they given another way to create String objects.

You can create String object with content "Anil" even
in the following manner.

String name = "Anil";

If you write syntax like this... internally java checks if this string
is already in String pool. If it is there.... it returns the reference
to existing String object.

If the object you are trying to create is not existing it will try to
create.... String "Anil" in String pool....

In this case only one object gets created whereas in the first
scenario 1000 object gets created... So you can imagine
how much memory will be saved with this concept....
------------------------------------------------------------------------------

So Finally if you say new String("Anil") always object gets
created

If you say String name = "Anil"; It will be checked in string pool
if the object doesn't exist then only String object with content "Anil" gets
created.

1 comment: