About String.intern () and new StringBuilder ( ""). Append ( ""). ToString () "java" appear before execution StringBuilder.toString ()

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.
Here Insert Picture DescriptionFor System, ctrl + left mouse button, you can see in the System class, the class is called directly
Here Insert Picture Descriptionin the class to see initializeSystemClass method, which has a Version
Here Insert Picture DescriptionView Version source you
Here Insert Picture Descriptioncan 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! ! !

Published 24 original articles · won praise 0 · Views 611

Guess you like

Origin blog.csdn.net/weixin_43896829/article/details/103840822