Why are Java strings considered immutable? I can say String name = "Paul";
and later on change name value to name = "Henry";
. Where is immutability coming from?
Asked
Active
Viewed 294 times
-6

tostao
- 2,803
- 4
- 38
- 61

Paul Odero
- 39
- 8
-
You are not changing the previous string object, instead you are making and assigning new object to `name`. – Adil Soomro May 14 '13 at 12:17
-
3Five Good Reasons: [Why String is immutable or final in Java](http://javarevisited.blogspot.in/2010/10/why-string-is-immutable-in-java.html) – Grijesh Chauhan May 14 '13 at 12:18
-
http://stackoverflow.com/questions/1552301/immutability-of-strings-in-java – Steve P. May 14 '13 at 12:18
3 Answers
3
A new string is created, they are definitely immutable and interned btw.
You can't do this :
String name = "Paul"; // in effect the same as new String("Paul");
name.setValue("Henry")
becuase a string is immutable you have to create a completely new object.

NimChimpsky
- 46,453
- 60
- 198
- 311
-
How and yet name is the object and its value has been changed to "Henry" ? – Paul Odero May 14 '13 at 12:20
-
@PaulOdero: `name` is not the object. `name` is a reference to a (String) object. At first it's a reference to the `"Paul"` object, later you change that reference to point to the `"Henry"` object. The `"Paul"` object does not change, because it is immutable. – jlordo May 14 '13 at 12:24
-
@jlordo Does both `"Paul"` `"Henry"` exists in String pool. so that intially `name` pointed to `"Paul"` and then to `"Henry"` – Santhosh May 05 '15 at 15:08
-
1
The object itself didn't change.
What you have done is the following
name <- String("Paul")
name <- String("Henry")
String("Paul") has been not been changed.
Try the following:
String a = "test";
String b = a;
a = "test2";
System.out.println(b);

Michal Borek
- 4,584
- 2
- 30
- 40
1
Distinguish between the variable: name, which is referring to a String and the String it refers to.
name originally pointed to the String "Paul", later you changed it to point somewhere else, "Paul" itself was unaffected.
Consider
String name = "Paul";
String name1 = name;
name = "Peter";
what does name1 refer to now?

djna
- 54,992
- 14
- 74
- 117