Chapter 2 issue of "in-depth understanding of the Java Virtual Machine"
In the book there is such an example:
public class RuntimeConstantPoolOOM{
public static void main(String[] args){
String str1=new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern()==str1);
String str2=new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern()==str2);
}
}
The authors note that due to the start JDK1.7 gradual "de-permanent generation", so if the two JDK1.6 returns false, JDK1.7 run will return a true a false.
Since JDK1.6 in, intern () method will first encountered instance of the string copied to the permanent generation, also cited the return of permanent generation instances of the string, and the string instance StringBulder created on the heap in Java , it is not necessarily the same references, returns false.
In JDK1.7, intern () implementation will not be replicated instance, in the example just cited the constant pool record for the first time, so the return is a reference to the string and the instance created by StringBuilder.toString () is the same .
str2 comparison returns false because the "java" string before executing StringBuilder.toString () has occurred, the string constant pool has its references, does not comply with the principle of "first appearance", and "Computer Software" this string is the first time, therefore return true.
Then there is a doubt, the "java" string appears where before? Obviously not appear directly in this class inside.
For System, ctrl + left mouse button, you can see in the System class, the class is called directly
in the class to see initializeSystemClass method, which has a Version
View Version source you
can see the constant pool at runtime, it has been automatically He joined the "java" string, so have "java" string constant pool.
As for any errors, welcomed the large cattle raised, thanks! ! !