Ravindra Jha Ravindra Jha - 2 months ago 8
Java Question

String created using new String(param) does actually contain param or reference to param from pool

I understand the difference between string created using new String(param) and using literal.

When String created using litleral like -

String str = "param";


so the variable str will contain reference from the String Pool.
My question is when we create string like -

String str1 = new String("param");


It will create an object in Heap with "param" as value and str1 will contain reference to the object in heap.
So the object created in heap actually contain the value "param" or contain reference from the string pool?

Answer

It will create an object in Heap with "param" as value and str1 will contain reference to the object in heap.

Both str and str1 point to String objects in the Heap. str is also in the String literal pool. All String objects in the String literal pool are on the heap from Oracle Java 6+

So the object created in heap actually contain the value "param" or contain reference from the string pool?

The String contains a char[] which will have the characters "param" and this will be the same reference to a char[] as in the String literal pool (implementation dependant)