-8

Since String is Immutable How can we will change String for Example

String s1="Hello";
  String s2="Manas";

Now I am making

s1=s1+s3;

It will Print "Hello Manas". So String s1 will change.

So how can u say that String is immutable?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177

1 Answers1

6

You're not changing the contents of "Hello", you're changing the value of the variable s1 to refer to a different string object entirely.

Immutability has nothing to do with changing the value of the variable - if you want to prevent that, you can make the variable in question final.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 1
    You're not changing the value of the reference - you're changing the value of the *variable* to be a different reference. (Just like `int x = 0; x = 5;` doesn't change what 0 means, it changes the value of `x` to 5.) – Jon Skeet Feb 20 '14 at 14:32
  • @JonSkeet Ah sorry, bad wording on my part. Fixed now. – Michael Berry Feb 20 '14 at 14:33
  • It not like (int x = 0; x = 5) it's like (final int x = 0; x=5;) So how can u change final variable. – manu198 Feb 20 '14 at 14:46