Quantcast
Channel: Learn Java Programming
Viewing all articles
Browse latest Browse all 39

Immutable String Objects : String Handling Java Tutorials

$
0
0

What is Immutable Objects ?

When you have a reference to an instance of an object, the contents of that instance cannot be altered

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 Reference

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 Referencing

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

The post Immutable String Objects : String Handling Java Tutorials appeared first on Learn Java Programming.


Viewing all articles
Browse latest Browse all 39

Trending Articles