String Concat With Same Reference? [duplicate]

纵饮孤独 提交于 2019-12-06 04:44:54

问题


Here is my code and I am now quite confuse about String pool and Heap storage by this output.

public class String1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String str = "abcd";
        String str1 = "" ;

        str1=str1+"abcd";

        if(str.equals(str1))
            System.out.println("True");
        else
            System.out.println("False");

        if(str == str1)
            System.out.println("True");
        else
            System.out.println("False");
    }
}

Now, I am creating String str and will be stored in string pool (Correct me if I am getting wrong!). Now after concat str1 with string "abcd" they both have same value. So, I think str and str1 should have same reference in String pool and So, 2nd if statement should print true but it prints false.

So, my question why str and str1 not getting same reference ?


回答1:


Java automatically interns (means, puts them into the String pool) String literals, not newly created Strings. See also https://stackoverflow.com/a/1855183/1611055.

Remember that Strings are immutable, so the + operator must create a new String - it can not append to the existing one. Internally, the + operator uses a StringBuilder to concatenate the strings. The final result is retrieved through StringBuilder.toString() which essentially does return new String(value, 0, count);.

This newly created String is not automatically put into the String pool.

Hence the str1 reference is different from str even though the strings have the same content. str points to a location in the string pool, while str1 points to a location on the heap.

If you add

str1 = str1.intern();

after str1 = str1 + "abcd"; to explicitly intern the newly created String, your second if statement returns true.

Alternatively, str1 = (str1 + "abcd").intern(); would have the same effect.




回答2:


In case of strings to compare the values we should use equals method as it compares values that are present in the string variables.

But when we choose to compare string variables using == it compares the addresses of the String object not the values so it will return false even if they have same values in it.




回答3:


you are right that the strings get added to the string pool. but == checks if both the objects are pointing to the same reference (to make it simpler pointing to the same memory location) in the string pool or not. whereas .equals() method check if the value of the both the object are same or not.



来源:https://stackoverflow.com/questions/36735934/string-concat-with-same-reference

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