string.toUppercase() created a new object in heap

2019-05-20 23:20发布

问题:

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.