-6

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?

tostao
  • 2,585
  • 3
  • 34
  • 58
Paul Odero
  • 39
  • 8

3 Answers3

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
  • 44,999
  • 57
  • 192
  • 304
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,544
  • 2
  • 28
  • 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,014
  • 11
  • 72
  • 114