Immutability

In java String objects are immutable. The meaning of immutable is that changes in string object are not possible in java or we can say all strings are constant.
But in program given below we are denying this fact that we can't change a string.

Example :


class str 
{
public static void main(String arg[]))
{
String obj1=new String("hello");
obj1= obj1+" world";
System.out.println(obj1);
}
}
//output:hello world

How it is possible if can't change string, then why above program is working properly.


Reason is when we try to concatenate "world" with obj1 string. Java created new string with "hello world", but original string is not changed.


After changing new string is created and for old string now there is no reference variable. So this object is cleaned by garbage collector.

Example :


class str
{
public static void main(String arg[]))
{
String obj1="hello";
String obj2="hello";
if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or not.
System.out.println("same object");
else
System.out.println("Different object");
}
}
//output:same object


When obj2 is created, in memory already one object with same value was there. java simply assigned that object reference to obj2.



both reference variable are pointing to same object, that's why output of program is same object.