比较两个字符串s =“ja”.concat(“va”);和s1 = s.intern(); with ==运算符返回false。为什么?

时间:2017-08-08 18:42:39

标签: java string string-comparison

  1. 对于Eg:当我在调用intern()方法后将两个字符串与==运算符进行比较时,它返回true。

    String name = "Wahab"; // in string literal pool
    String fullName = new String("Wahab"); // new string in heap
    String f = fullName.intern(); // pushing into string literal pool
    System.out.print(name == f); // **true**
    
  2. 使用Concat并调用intern(),==运算符返回true。

    String name = "Wahab".concat("Shaikh"); // concat with new string
    String fullName = name.intern(); // invoke intern to push into string literal pool
    System.out.print(name == fullName); // **true**
    
  3. 拥有更少的字符,连接并调用intern()然后返回false。

    String a = "ja".concat("va"); // concat with fewer characters
    String a1 = a.intern(); // push into literal pool and assign to new variable
    
    System.out.print(a == a1); // **false**
    

    为什么第三个输出是假的? 请帮忙。

1 个答案:

答案 0 :(得分:2)

来自String.intern() doc:

  

调用实习方法时:
   - 如果池已经包含等于此字符串对象的字符串(由equals(Object)方法确定),则将返回池中的字符串
   - 否则,此String对象将添加到池中,将返回对此String对象的引用

所以"ja".concat("va").intern()返回池中已经存在的String“java”的实例(因为该字符串已经存在于JVM的很多地方并且显然是实例化的)。在您的代码中,a1指向预先存在的实习实例,a指向您刚刚构建的实例。

"Wahab".concat("Shaikh").intern()返回刚刚创建的字符串“WahabShaikh”的实例。