String extension: intern() method

String s1 = new String("1") + new String("1");//s1变量记录的地址为:new String
s1.intern();//在字符串常量池中生成"11"。如何理解:jdk6:创建了一个新的对象"11",也就有新的地址;jdk7:此时常量池中并没有创建"11",而是创建了一个指向堆空间中new String("11")的地址;
String s2 = "11";
System.out.println(s1 == s2);//jdk6:false;jdk7:true

Summarize the use of intern() method in String:

In jdk6:

Try to put this string constant pool into the string constant pool.

If there is in the constant pool, there will be no method. Return the address of the object in the existing constant pool;

If not, it will make a copy of this object, put it into the string pool, and return the object address in the string pool;

In jdk7:

Try to put this string constant pool into the string constant pool.

If there is in the constant pool, it will not be placed. Return the address of the object in the existing constant pool;

If not, it will copy the reference address of the object, put it into the constant pool, and return the reference address in the constant pool;

Guess you like

Origin blog.csdn.net/guorui_java/article/details/109787051