Easy tech stuff!

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.

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png

5 Comments on “Simple example to demonstrate that String object is immutable”

  1. 1 boopathiraja said at 5:35 am on May 16th, 2008:

    Really Good..

  2. 2 techtamasha.com » Blog Archive » Difference between String and StringBuffer/StringBuilder in Java said at 11:33 am on June 24th, 2008:

    [...] A simple Example to demonstrate that String object is Immutable [...]

  3. 3 vanitha said at 12:50 pm on February 2nd, 2010:

    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………

  4. 4 Nischal Shetty said at 5:06 pm on February 3rd, 2010:

    @vanitha
    Glad you found it useful :)

  5. 5 Amit said at 1:19 pm on August 20th, 2010:

    Really awesone .Thanks for clear vision.


Leave a Reply