Prasoon said:
Considering the statements
a) String s1="Hello";
b) i ) String s="Hello";
and
ii) String s=new String("Hello");
I thought both the statements b(i) and b(ii) were identical before I
came to know that "object creation" is guaranteed in b (ii) whereas it
is not guaranteed in b(i) after statement (a) has been executed!!!!
No, they are not equivalent. In terms of the produced bytecode, the
former would be an ldc followed by an astore; the latter would be an
anew, dup, ldc, invokespecial, aload. The ldc causes reuse of the string
literal (specifically, it is an interned string representation), but the
anew definitely causes creation of a new object, which may of course
cause memory to run out. However, unless I am mistaken, the new String
will share the same character buffer, so if that causes an
OutOfMemoryError, chances are that your program is about to run out of
memory anyways.
Anyways is there anything mentioned about the "String Pool" in the
JLS?????
JLS §3.10.5 String Literals:
Each string literal is a reference (§4.3) to an instance (§4.3.1,
§12.5) of class String (§4.3.3). String objects have a constant value.
String literals-or, more generally, strings that are the values of
constant expressions (§15.28)-are "interned" so as to share unique
instances, using the method String.intern.
That is as much detail as it goes into, since the Java developers
decided eons ago that it would be more productive to separate the core
Java API (especially java.lang) from the language specification itself.
The String.intern() method documentation is the component which actually
describes the pool:
A pool of strings, initially empty, is maintained privately by the class
String.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object
is added to the pool and a reference to this String object is returned.