The difference between the two methods of String object instantiation
- 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
- 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.
- The concept of the pool: String object (constant) pool, the main purpose of the object pool is to achieve data sharing processing
- 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