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 } }

  1. ![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)
  2. ```java
  3. package test;
  4. public class Main {
  5. public static void main(String[] args) {
  6. String s1 = "WTY2002"; //指向常量池”WTY2002”
  7. String s2 = "java"; //指向常量池”java”
  8. String s4 = "java";//指向常量池”java”
  9. String s3 = new String("java");//指向堆中对象
  10. System.out.println(s2 == s3); // F
  11. System.out.println(s2 == s4); //T
  12. System.out.println(s2.equals(s3));//T
  13. System.out.println(s1 == s2); //F
  14. }
  15. }

image.png

  1. package test;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Person p1 = new Person();
  5. p1.name = "WTY2002";
  6. Person p2 = new Person();
  7. p2.name = "WTY2002";
  8. System.out.println(p1.name.equals(p2.name));//比较内容: True
  9. System.out.println(p1.name == p2.name); //T 均指向常量池中地址
  10. System.out.println(p1.name == "WTY2002"); //T 均指向常量池中地址
  11. String s1 = new String("bcde");
  12. String s2 = new String("bcde");
  13. System.out.println(s1==s2); //False
  14. }
  15. }
  16. class Person {
  17. public String name;
  18. }

image.png