Simple example to demonstrate that String object is immutable
Posted: February 19th, 2008 | Author: Nischal Shetty | Filed under: Java | 5 Comments »In my post ‘Difference between String and StringBuffer/StringBuilder’ I told you stuff like String object is immutable( meaning the value stored in the object cannot be changed) and that when you perform operations such as concat or replace, internally a new object is created to hold the result.
Below is a simple example that will make you believe that what I said about String object is indeed true!
String s = “Let’s test”;
s.concat(” if the String object is IMMUTABLE”);
System.out.println(s);
s = s.concat(” if the String object is IMMUTABLE”);
System.out.println(s);
The output of the above code will be:
Let’s test
Let’s test if the String object is IMMUTABLE
That’s all people! The above piece of code proves that String is immutable and hence the results of operations like concat etc. should be stored into a new object.












Really Good..
[...] A simple Example to demonstrate that String object is Immutable [...]
Its very nice..iam very clear about String concept now…this website ,this explanation really helped me to got rid of my pro longed doubts abt the diff b/w string/string buffer..its really good..many thanks………
@vanitha
Glad you found it useful
Really awesone .Thanks for clear vision.