1

If a String object is immutable then why is it printing "Help"?

The String object s1 shouldn't be modified according to its immutability feature. I am confused for years, please help me understand this:

Code

public static void main(String[] args) {

    String s1 = "Hello";

    s1 = "Help";

    System.out.println(s1);
}

Output

Help
rbento
  • 9,919
  • 3
  • 61
  • 61
Arun Raaj
  • 1,762
  • 1
  • 21
  • 20
  • The assignment `s1="Help";` creates a new object in the string pool and assigns the reference to `s1`. The original `"Hello"` string in the pool has not been modified. – Tim Biegeleisen Jun 23 '16 at 10:41

1 Answers1

3

Your second assignment actually is changing the String that s1 references.

There is still a String of "Hello" in existence (in the pool) which cannot be changed.

The behavior you described would be achieved by making s1 final - in which case you would get a compiler error if you tried to change the value the String s1 references.

saml
  • 794
  • 1
  • 9
  • 20