1. What happens for "String s1 =" abc "?
At compile time, the literal representation is written to the "constant pool" part of the class class for the class that contains this code.
When the class is loaded, the string literal representation in the classfile constant pool is read, and a new String object is created from it. This string is then interned, and the reference to the interned string is then "embedded" in the code.
At run time, a reference to a previously created / interned string is assigned to s1
. (When executing this statement, no string or internment is created).
I assume that a String object is being added to the pool in the String class as an interned string?
Yes. But not when the code is executed.
Where is he located? "Permanent generation" or just a heap (as a data element of an instance of a String Class)?
It is stored in the heap's permgens. (The String class has no static fields. The JVM string pool is implemented in native code.)
2. What happens for "String s2 =" abc "?
Nothing happens at boot time. When the compiler created the cool file, it reused the same constant pool entry for the literal that was used for the first use of the literal. Thus, the String reference used by this statement is the same as the previous statement.
I think no object has been created.
Right.
But does this mean that Java Intepreter needs to look for all interned strings? will this cause any performance issue?
No and no. The Java interpreter (or JIT-compiled code) uses the same links that were created / embedded for the previous statement.
3.Seems String s3 = new String ("abc") does not use the intern string. Why?
It is harder than that. The constructor call uses the interned string, and then creates a new string and copies the characters of the interned string to the new String representation. A new line is assigned to s3
.
Why? Since new
is always specified as creating a new object (see JLS), and the String
constructor is indicated as copying characters.
4.Will String s5 = new String ("def") create any new interned string?
At boot time (for "def") a new interned string is created, and then at runtime a new String object is created, which is a copy of the interned string. (See previous text for more details.)