Java immutable string object



[box]

What is Immutable Objects ?

When you have a reference to an instance of an object, the contents of that instance cannot be altered
[/box]
Consider the following example –

class ImmutableString {
public static void main(String[] args) {

	String myString = new String("I am living in India");
	System.out.println( myString );

	myString.replaceAll( "India" , "USA" );
	System.out.println( myString );

	}
}

Output of Program :

I am living in India
I am living in India

Explanation : Immutable String Objects

In the above example, we can see that

myString.replaceAll( "India" , "USA" );

it will create another string i.e –

I am living in USA

Immutable String Concept – Before ReplaceAll
though object is created for “I am living in USA” string but reference variable “myString” is still not referring to new string. We need to specify the reference explicitly using following assignment –

myString = myString.replaceAll( "India" , "USA" );

Immutable String Concept – After ReplaceAll

class ImmutableString {
public static void main(String[] args) {

    String myString = new String("I am living in India");
    System.out.println( myString );

    myString = myString.replaceAll( "India" , "USA" );
    System.out.println( myString );

    }
}

and output will be like this –

I am living in India
I am living in USA