Consider the following example.
String str = new String();
str = "Hello";
System.out.println(str); //Prints Hello
str = "Help!";
System.out.println(str); //Prints Help!
Now, in Java, String objects are immutable. Then how come the object str
can be assigned value "Help!". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?
Edit:
Ok. I am now getting it, but just one follow-up question. What about the following code:
String str = "Mississippi";
System.out.println(str); // prints Mississippi
str = str.replace("i", "!");
System.out.println(str); // prints M!ss!ss!pp!
Does this mean that two objects are created again ("Mississippi" and "M!ss!ss!pp!") and the reference str
points to a different object after replace()
method?
If
HELLO
is your String then you can't changeHELLO
toHILLO
. This property is called immutability property.You can have multiple pointer String variable to point HELLO String.
But if HELLO is char Array then you can change HELLO to HILLO. Eg,
Programming languages have immutable data variables so that it can be used as keys in key, value pair.
String is immutable. Which means that we can only change the reference.
The object that
str
references can change, but the actualString
objects themselves cannot.The
String
objects containing the string"Hello"
and"Help!"
cannot change their values, hence they are immutable.The immutability of
String
objects does not mean that the references pointing to the object cannot change.One way that one can prevent the
str
reference from changing is to declare it asfinal
:Now, trying to assign another
String
toSTR
will cause a compile error.Regarding the replace part of your question, try this:
String class is immutable, and you can not change value of immutable object. But in case of String, if you change the value of string than it will create new string in string pool and than your string reference to that value not the older one. so by this way string is immutable. Lets take your example,
it will create one string "Mississippi" and will add it to String pool so now str is pointing to Mississippi.
But after above operation, one another string will be created "M!ss!ss!pp!" and it will be add to String pool. and now str is pointing to M!ss!ss!pp!, not Mississippi.
so by this way when you will alter value of string object it will create one more object and will add it to string pool.
Lets have one more example
this above three line will add three objects of string to string pool.
1) Hello
2) World
3) HelloWorld
String in Java in Immutable and Final just mean it can't be changed or modified:
Case 1:
Case 2: