String Concat With Same Reference? [duplicate]

梦想与她 提交于 2019-12-04 11:26:14
Andreas Fester

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.

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.

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.

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