Search code examples
javastringuppercase

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


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.


Solution

  • 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.