I was curious as to why Strings can be created without a call to new String()
, as the API mentions it is an Object
of class
java.lang.String
So how are we able to use String s="hi"
rather than String s=new String("hi")
?
This post clarified the use of ==
operator and absence of new
and says this is due to String
literals being interned or taken from a literal pool by the JVM
, hence Strings
are immutable.
On seeing a statement such as
String s="hi"
for the first time what really takes place ?
Does the
JVM
replace it like thisString s=new String("hi")
, wherein an Object is created and"hi"
is added to the String literal pool and so subsequent calls such asString s1="hi"
are taken from the pool?Is this how the underlying mechanism operates? If so, then is
String s=new String("Test"); String s1="Test";
the same as
String s="Test"; String s1="Test";
in terms of memory utilization and efficiency?
Also, is there any way by which we can access the String Pool to check how many
String
literals are present in it, how much space is occupied, etc.?
No. What really happens is - the String Literals are resolved during compile time and interned (added to the String constants pool) as soon as the class is loaded / initialized or lazily. Thus, they are made available to the classes within the JVM. Note that, even if you have a String with value
"hi"
in the Strings constants pool,new String("hi")
will create another String on the heap and return its reference.No, in the first case 2 "Test" Strings are created. One will be added to the String constants pool (assuming it is not already present there) and another on the heap. The second one can be GCed.In the second case, only one String literal is present in the String constants pool and there are 2 references to it (
s
ands1
).I don't think we can see the contents of the String constants pool. We can merely assume and confirm the behavior based on our assumptions.