3

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.

Mohit Tyagi
  • 2,788
  • 4
  • 17
  • 29
ZerekSees
  • 91
  • 1
  • 10
  • 2
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Naman Sep 25 '17 at 05:18
  • 1
    When you create String literals that goes to String pool. For Everything else a new Object is created. – Pramod Sep 25 '17 at 05:23
  • 1
    `==` is not compare 2 strings, it compares 2 object containt reference to these 2 strings so 2 object are difference. String object is immutable so I think it will go to String pool. Read more about `immutable vs mutable object`, `string pool vs heap` – Bui Anh Tuan Sep 25 '17 at 05:27

2 Answers2

2

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.

msmani
  • 730
  • 1
  • 7
  • 24
0

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.

Mohit Tyagi
  • 2,788
  • 4
  • 17
  • 29