Simple example to demonstrate that String object is immutable

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.

30 comments

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

  2. @vanitha
    Glad you found it useful :)

  3. Really awesone .Thanks for clear vision.

  4. Really nice and very useful for me…

  5. Really a simple example to understand. Very useful

  6. its gud to understand clearly.

  7. Hello,
    String is Immutable but i dont support the above code because when u declare s =”lets test”
    and later when u cancat as s.concat(“if the String is IMMUTABLE”)
    and later u passed to s
    now when u say System.out.println(s);

    the previous value of s=”lets test” has been changed to s=”lets test if the string is immutable”

    afterall IMMUTABLE means the value stored in that object will not change but it changed here………

  8. Because it is immutable, I had to pass the value of s.concat() back to s. If it was mutable, then I would just do s.concat() and it should have worked ;)

    Try this:

    String s = “test”;
    s.concat(” does this print?”);
    System.out.println(s);

  9. ya that will give u only test as output
    bcoz at that particular instance s holds value as test
    no suprise in that
    when u use String s=”test”
    and s=”Hello”
    System.out.println(s);
    then output should be test not hello but this doesnt happens
    then how can u say that string is mutable

  10. There is a surprise in that. Try

    StringBuilder s = new StringBuilder(“test”);
    s.append(” does this print?”);
    System.out.println(s);

    What do you get?

  11. You need to understand “variables” and “objects” before you can fully get this. Let me try :

    Variable is a container.
    Object is something that fits inside a container.

    So, we can put an object inside a variable. Based on the datatype (String, int, long etc), you can put specific objects into specific variables.

    Now,

    String s;

    ‘s’ is a variable.

    “test” is an object.

    String s = “test”;

    Here I have only put object “test” into variable ‘s’. Any operation such as s.concat() that I now perform, I am really performing it on the object “test” and not on the variable.

    Since I am performing operations on the object, the operations should modify the object, which happens always except in the case of immutable objects like String.

  12. hey…it is really gud explanation. keep it up. Do well…

  13. very useful for me also…

  14. Hey pradeep nischal didnt said that string is mutable it’s immutable…

  15. I kind of agree to Pradeep..Although whatever you have written is correct but it does not justify why Strin is immutable…
    You just point out the difference between Strings Concat function and StringBuffer append function..
    String Class — concat method
    public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
    return this;
    }
    char buf[] = new char[count + otherLen];
    getChars(0, count, buf, 0);
    str.getChars(0, otherLen, buf, count);
    return new String(0, count + otherLen, buf);
    }
    In this it returns a new string and does not assign the new value to this or itself..
    whereas StringBuilder append function
    public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
    }
    If you see it returns this…..the same object ..it appends to it…
    it means if tried to immitate in String..it would be somewhat like this..
    s=s.concat(“Strin2″);
    We would have to assin to it..as the methods works on different object …String does it on a new String object whereas Stringbuffer on this..

    String is immutabke but not really shown in this example..

  16. Let me give it in more real sense.Would not be difficult if u think how it is stored in memmory..

    Immutable: As sounds means the same… It is not destroyable… Like immunity…
    (all memmory reference are immaginary numbers dont comment that this no is not possible and all…)

    StringBuffer name1 = new StringBuffer(“Vinay”); //say in memmory name1=20102H (which stores Vinay) —
    StringBuffer name2 = name1; //name2=20102H (which contain Vinay)
    if(name1==name2) //true as both contains 20102H memmory address
    System.out.println(“names are same”);
    String address1 = new String(“Mumbai”); //say in memmory name1=20103H (which stores Mumbai) —
    String address2 = address1 ;
    if(address1==address2) //true as both contains 20103H memmory address
    System.out.println(“address are same”); //it would print this
    //Till now i proved nothing about immutability
    //Now lets try to add a string
    name2= name2.append(“Fool”); //name2 would still contain 20102H whose value is now (Vinay Fool) at this point Vinay is lost it is distroyed
    if(name1==name2) //true as both contains 20102H memmory address
    System.out.println(“names are still same”);
    address2=address2+”Fool”; //address2 would point to new address 20104H whose value is (Mumbai Fool)
    if(address1==address2) //not same address1 points to 20103H (which contains Mumbai) and address2 points to 20104H (which contains Mumbai Fool)
    System.out.println(“address are still same”);
    output
    names are same
    address are same
    names are still same

    What happened why did not address are still same came in output

    //it would not print address are still same this is because address1 holds “Mumbai”…its not destroyed unless pointed to something unless…In memmory “Mumbai” of address would still be there..

    It means value assigned to String cannot be changed , if changed it would create a new memmory space where the new value is stored and not that the same memmory is remodified in internal pool…I would have liked to show it using memmory location to show that value of memmory location does not change but whenever String value changes in String it gets referrenced to new memmory location unlike in StringBuffer where the value changes in same memmory location…

  17. This is the main reason why String is made immutable..Security wise the same memmory location cannot be changed and how it helps lets take another eaxmple.
    If you check class “File” you would see
    static final String pathSeparator
    now suppose there is two files with same name “Authorize.txt” one in (you have authority to read and write file in “d://files//”); —
    and other in d://files//secure// — which you dont have access to.
    You have access to only d://files//
    final StringBuffer filepath = new StringBuffer(“d://secure//”);
    System.out.println(filepath);
    //now you open the file ..usin file open
    //and then change the path
    filepath.append(“//secure//”);
    System.out.println(filepath); //prints d://file//secure//
    //now you if write anything into that file it would start writing
    into d://file//secure//Authorize.txt instead of d://files//Authorize.txt … This is only a if- it would be example you cannot do this in current Class File as all are String..

    And this would not work with String

    final String filepath = new String(“d://file//”);
    System.out.println(filepath);
    filepath=filepath+”secure//;
    this above statement would create a new memmory location with String d://file//secure// and when it tries to assign to filepath it shows it is final and it cannot be changed whereas in Stringbuffer it does not create new memmory location but changes the value in same memmory location .. :)
    would give compile error saying filepath is final when String…

    one reference which I liked…

    http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

  18. thanks good posts..

  19. Nice tutorial..
    Thanks a lot.

  20. Indeed very helpful !

  21. @vinay guru:excellent comment

  22. @Vinay I’m sorry I do not agree with that… It’s not security that needed String to be immutable….

    Strings were made immutable because at any given point multiple variables can refer to the same object… It would lead to inconsistencies if the objects could be changed.

  23. Thank you

  24. Its really good and helpful for those who are novice…

  25. Nice clarification…

  26. Both Nischal and Vinay are trying to say the same thing…here’s Nischal’s example with Vinay’s explanation….

    String s = “Let’s test”;
    //this object(“Let’s test”) is created,say,in memory location: 2012

    s.concat(” if the String object is IMMUTABLE”);
    //since String objects are immutable, the object in memorylocation:2012 cannot be destroyed, replaced or overridden. Instead s.concat creates a new object(“Let’s test if the String object is IMMUTABLE” ) in the next available memory location,say,2022.

    System.out.println(s);
    //since s still references the memorylocation:2012, it prints only the first object “Let’s test”.

    s = s.concat(” if the String object is IMMUTABLE”);
    //Step 2 gets repeated again. s.concat creates a new object(“Let’s test if the String object is IMMUTABLE” ) in the next available memory location:2065. However the additional assignment of s changes the scenario totally. Now s is made to reference the memorylocation:2065.

    System.out.println(s);
    //Since s points to memorylocation:2065, it will print the object “Let’s test if the String object is IMMUTABLE”. Hence the output!!

    The output of the above code will be:

    Let’s test

    Let’s test if the String object is IMMUTABLE

  27. thanks all of one……..

Leave a comment