Before talk about immutable, first look at what happen in the computer memory when we create a string variable.
String a="matara";
Here reference variable called "a" is created inside the stack memory and object with the value of "matara" is created inside heap memory of the computer. Actually this object is created inside the memory area called String pool.
Now let's say I will create another String named "b" with the same value as above
String b = "matara";
Here what happen is reference variable called "b" is created inside the stack memory and this reference variable will also point to the same object which String "a" is pointing to.The most important point here is no other object is created inside the String pool with the value of "matara".The reason for not to creating another object is , each time when creating a new String literal , JVM checks whether that String value is already in the String pool.If so, without creating new String object , pointing to the same String object.
Now move to the our topic.
Here both "a" and "b" reference variables are pointing to same object. Suppose I change the value of the String "a" as "colombo".
a="colombo";
If String was mutable now what happen is "matara" will be changed as "colombo" . Then value of the String "b" also become to "colombo" since both "a" and "b" were pointing to the same object. But actually what should happen is value of the variable "b" should still be as "matara" since we didn't change its value. To achieve this purpose String objects are created as immutable.
Now, sometimes you may have a confusion, can't we change the value of the variable "a" .Actually we can . You no need to bother about anything. Java will internally solve this problem . Actually what happen when you change the value of the variable "a" as "colombo" is, separate object with the value of "colombo" is created inside the heap memory and variable "a" will be pointed to that object from that onwards . And still reference variable "a" is pointing to the object of the value with "matara".
By referring the below code segment you will be able to get more clear idea what I have discussed so far.
public class ImmutableTest {
public static void main(String[] args) {
String a= "matara";
String b= "matara";
System.out.println("Before changing the value....");
System.out.println("value of a = "+a);
System.out.println("value of b = "+b);
System.out.println();
a="colombo";
System.out.println("After changing the value....");
System.out.println("value of a = "+a);
System.out.println("value of b = "+b);
}
}
No comments:
Post a Comment