intern方法:
当调用intern方法时,如果池已经包含一个等于此String对象的字符串(用equals(Object)方法确定),则返回池中的字符串。否则,将此String 对象添加到池中,并返回此 String对象的引用
解读:
- b.intern()方法最终返回的是常量池的地址(对象) ```java package test;
public class Main { public static void main(String[] args) { String a = “WTY2002”; //a 指向 常量池的 “WTY2002” String b =new String(“WTY2002”);//b 指向堆中对象 System.out.println(a.equals(b)); //T System.out.println(a==b); //F //b.intern() 方法返回常量池地址 System.out.println(a==b.intern()); //T System.out.println(b==b.intern()); //F } }
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21705001/1639034620141-bf824ef6-40fa-4d14-802a-17b410e59a55.png#clientId=ue98bc489-d3b7-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=252&id=u1e655728&margin=%5Bobject%20Object%5D&name=image.png&originHeight=206&originWidth=609&originalType=binary&ratio=1&rotation=0&showTitle=false&size=17123&status=done&style=none&taskId=ub8f4347a-54ae-4648-aa7d-b212ce39fee&title=&width=744)
```java
package test;
public class Main {
public static void main(String[] args) {
String s1 = "WTY2002"; //指向常量池”WTY2002”
String s2 = "java"; //指向常量池”java”
String s4 = "java";//指向常量池”java”
String s3 = new String("java");//指向堆中对象
System.out.println(s2 == s3); // F
System.out.println(s2 == s4); //T
System.out.println(s2.equals(s3));//T
System.out.println(s1 == s2); //F
}
}
package test;
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.name = "WTY2002";
Person p2 = new Person();
p2.name = "WTY2002";
System.out.println(p1.name.equals(p2.name));//比较内容: True
System.out.println(p1.name == p2.name); //T 均指向常量池中地址
System.out.println(p1.name == "WTY2002"); //T 均指向常量池中地址
String s1 = new String("bcde");
String s2 = new String("bcde");
System.out.println(s1==s2); //False
}
}
class Person {
public String name;
}