问题
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**
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**
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