string.toUppercase() created a new object in heap or string pool

陌路散爱 提交于 2019-12-08 01:08:33

问题


If we use toUpperCase() method of String class, does it put the object in the heap rather than creating it in the String pool. Below is the code, when I ran, I could infer that newly created string objects are not in String pool.

public class Question {
    public static void main(String[] args) {
        String s1="abc";
        System.out.println(s1.toUpperCase()==s1.toUpperCase());
    }
}

Output of the above code return false. I know about "==" and equals() difference but in this question I am wondering why the two created strings are not equal. The only explanation could be that they are not created in the String pool and are two different objects altogether.


回答1:


Java automatically interns String literals. check this answer, but when you use toUpperCase() it creates a new instance of the string, using new String(), that's why both the objects are different.




回答2:


The "==" operator compares the value of two object references to check whether they refer to the same String instance, so in this case toUpperCase() creates a new instance of String that's why it return false.

On the other hand equals() method compares the "value" inside String instances irrespective of the two object references refer to the same String instance or not, and so it returns true.



来源:https://stackoverflow.com/questions/46398042/string-touppercase-created-a-new-object-in-heap-or-string-pool

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