Comparing two Strings s = “ja”.concat(“va”); and s1=s.intern(); with == operator returns false. Why?

半城伤御伤魂 提交于 2020-01-06 06:43:07

问题


  1. For Eg: When I compare two strings with == operator after I call intern() method it returns 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. Using Concat and invoke intern(), == operator returns 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. Having fewer chars, concatenate and invoke intern() then it returns 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**
    

    Why is the third output false? Please help.


回答1:


From String.intern() doc:

When the intern method is invoked:
- if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned.
- Otherwise, this String object is added to the pool and a reference to this String object is returned.

So "ja".concat("va").intern() returns the instance of String "java" that already exists in the pool (because that string already exists in a lot of places in the JVM and is apparently interned). In your code, a1 points to the pre-existing interned instance, and a points to the instance you just built.

And "Wahab".concat("Shaikh").intern() returns the instance of String "WahabShaikh" that you just created.



来源:https://stackoverflow.com/questions/45575811/comparing-two-strings-s-ja-concatva-and-s1-s-intern-with-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!