Hi,
According to "Java 2 A Beginner's Guide" by Herbert Schildt, Strings are immutable, i.e., once created you can't change them. However, I am playing in Eclipse and noticed that the following does in fact work:
String str = new String("Foo");
System.out.println(str);
str = "Bar";
System.out.println(str);
And the output is:
Foo
Bar
I had expected this to fail if a String is immutable. And yet I was able to change a String object (str) that initially held "Foo" to subsequently hold "Bar". Any ideas why this works?
Gina
Comments
String str = new String("Foo");
System.out.println(str);
str = 145; //str = "145" <--would work
System.out.println(str);
And the output is:
Foo
error
Initially [color=Blue]str[/color] is a String [u][italic]reference variable[/italic][/u] whose reference points to another string that has a value of "Foo".
The program then creates a new string with value "Bar" and sets the reference of [color=Blue]str[/color] to it. The value of the "Foo" string is still not changed.
If you like try the following code
[code]public class ImmutableString {
public static void main(String[] args) {
String str = new String("Foo");
String str2 = str;
str = "Bar";
System.out.println(str);
System.out.println(str2);
// mutableArray
int[] mutableArray = {1,2,3};
int[] mutableArray2 = mutableArray;
mutableArray[0] = 99;
for (int pointer=0; pointer<mutableArray.length; pointer++)
System.out.println("mutableArray element " + pointer + " is: " + mutableArray[pointer]);
for (int pointer=0; pointer<mutableArray.length; pointer++)
System.out.println("mutableArray2 element " + pointer + " is: " + mutableArray2[pointer]);
}
}[/code]
regards, se
I think you don't understand what "Strings are immutable" mean, so let me explain: if you have a primitive int variable with the value of 5 and you add 7 the result will 12, that means the value of int is mutable. but when you have a reference to a string like str = new String("Foo") and you assign an different string to the variable the old string is abandoned and the reference is redirected to the new string assigned. so with strings not the string is mutable but the reference to the string is mutable. in the end "Strings are immutable" is true and what you have done in eclipse is not changing a string, but assigned an other string to your variable. hope, you understand.