I am facing one easy question and I want your help. I am trying to understand immutable objects and I have read that Strings belongs to that category, meaning that their values cannot be changed after they are created. What this mean? I have create the following code and it's change fine:
Do I missed something?
Now we have created a String object with the value "Bacon is delicious". When we try to add " and nutritious!" to that object....well, we can't. Strings are immutable. So Java actually creates a whole new object, with the value "Bacon is delicious and nutritious!" and assigns it to test. The original String object containing "Bacon is delicious" still exists, we just don't have a variable pointing to it.*
*There was also a String object " and nutritious!" created, but String creation is a little off-topic.
However, if you have an object that never changes once its created, it's called immutable. String is such a class. Once you've created a String (remember that you create an instance of a String when you use a String literal), you can never change the value of that String.
Just take a String reference, and try calling any of its methods. You won't be able to change anything about the variable.
The first object that 's' references is a String, "defaultValue." This object is immutable. It will always be "defaultValue."
But you can reassign the variable to point to another object. "newValue" is an entirely different String object (also immutable). When you assign 's' to point to this second String, the first String object, "defaultValue" remains unchanged. It's simply no longer referenced by 's'.
In my example when I reassign the String variable to 'newValue' a new reference value was created with the old value existing but without any reference to it.
So I have to be careful when creating immutable objects because of leaving them unused in the memory until garbage collector runs.
Thanks a lot
naro pad wrote:...In my example when I reassign the String variable to 'newValue' a new reference value was created with the old value existing but without any reference to it...
You got it!
naro pad wrote:... So I have to be careful when creating immutable objects because of leaving them unused in the memory until garbage collector runs...
Well, that's a more complex issue that goes beyond immutable objects (and is further complicated by the String pool). But you have the right idea, because unreferenced objects will contine to exist in memory until collected.
String s = "defaultValue";
creates a String object with a value of 'defaultValue'. it creates a String reference called 's' that has the address of the object written down on it.
s = "newValue";
creates a new String object with a value of 'newValue'. The old address stored in 's' is erased, and the new address is written on it. The old object with 'defauleValue' still exists somewhere. You simply don't have the address anymore so you can't find it.