The difference between the instantiation method of String objects and the intern() method to realize the use of manual pooling

The difference between the two methods of String object instantiation

  1.    Direct assignment: Only one instantiated object is generated, and the library is automatically saved in the object pool to realize the reuse of string instances
  2. Construction method: Two instantiated objects will be generated, and they will not be automatically pooled. Object reuse cannot be achieved, but the intern() method can be used to manually pool them.
  3. The concept of the pool: String object (constant) pool, the main purpose of the object pool is to achieve data sharing processing
  4. The use of intern method:

Example:

package day04;

public class StringIntern {
public static void main(String[] args) {
	System.out.print(" 未使用intern()方法手工入池前-->");
	String strA = "SCP";
	String strB = new String ("SCP");
	System.out.println(strA == strB);
	System.out.print(" 使用intern()方法手工入池后-->");

	String strC = "SCP";
	String strD = new String ("SCP").intern();
	System.out.println(strC == strD);
}
}
输出结果:  
             未使用intern()方法手工入池前-->false
             使用intern()方法手工入池后-->true

 

 

Guess you like

Origin blog.csdn.net/qq_41663470/article/details/112966114