Wednesday, May 11, 2011

String Pool

Question : Strings can be created as follows in Java:
String str=new String("sumant");

or

String str="sumant";

Which one is better?

Answer:
String str=new String("sumant"); is better because while garbage collector starts collecting garbage, it will not collect objects in the pool, it will keep those objects in the pool, because these objects will be required in case in future same String objects are created.

by String str=new String("sumant"); , objects are not in the pool, so these can be garbage collected.