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.?
s = "hi"
tos = new String("hi")
? I don't see how this solved anything except adding a new layer, now you'll needs = new String(new String("hi"))
and in the end you need an infinite termnew String(new String(...
. If by the rhs"hi"
you meant something that isn't a string you should use a different syntax. – Glaab.class
file in the first place is the compiler. ;) – Dulcet