Sunday, 7 December 2014

WAP to test the immutablility of strings

//Test.java
class  Test
{
public static void main(String[] args)
{
String s1 ="data";
String s2="base";

//join s1 and s2 and store in s1
s1=s1+s2;
System.out.println(s1);
}
}

/*And the output of the program is "database" .It seems that the string s1 content is modified.
 Earlier s1 got "data" and s2 had "base". After s1+s2 they are joined and the total string
 becomes "database". This string is assigned to s1 again. So s1 appears to be mutable.
  But we learned that strings are immutable.

  s1 is definitly immutable. But then why the output of the program is like that ?In the program,
  jvm creates two object s1 and s2 separately. when s1+s2 is done, jvm creates a new object
  and stores the string "database" in that object.But it does not modify the contents of the string s1.
  After creating the new object, the reference s1 is adjusted to refer to that new object. The point
  we should observe here that the contents of the string s1 are not modified.this is the reason
  , strings are called immutable .the old object that contains "data" has lost its reference .so it is
  called a 'unreferenced object' and garbage collector will remove it from memory.

No comments:

Post a Comment