Immutability of Strings in Java

Viewed 102954

Consider the following example.

String str = new String();

str  = "Hello";
System.out.println(str);  //Prints Hello

str = "Help!";
System.out.println(str);  //Prints Help!

Now, in Java, String objects are immutable. Then how come the object str can be assigned value "Help!". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?

Edit:

Ok. I am now getting it, but just one follow-up question. What about the following code:

String str = "Mississippi"; 
System.out.println(str); // prints Mississippi 

str = str.replace("i", "!"); 
System.out.println(str); // prints M!ss!ss!pp! 

Does this mean that two objects are created again ("Mississippi" and "M!ss!ss!pp!") and the reference str points to a different object after replace() method?

26 Answers

The Object string - methods itself is made to be "immutable". This action produces no changes: "letters.replace("bbb", "aaa");"

But assigning data does cause changes to the Strings content to change:

    letters = "aaa";
    letters=null;
    System.out.println(letters);
    System.out.println(oB.hashCode());
    System.out.println(letters);
    letters = "bbbaaa";
    System.out.println(oB.hashCode());
    System.out.println(letters);

//The hashcode of the string Object doesn't change.

If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

You can have multiple pointer String variable to point HELLO String.

But if HELLO is char Array then you can change HELLO to HILLO. Eg,

char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this

Programming languages have immutable data variables so that it can be used as keys in key, value pair.

I would explain it with simple example


consider any character array : e.g. char a[]={'h','e','l','l','o'}; and a string : String s="hello";


on character array we can perform operations like printing only last three letters using iterating the array; but in string we have to make new String object and copy required substring and its address will be in new string object.

e.g.

***String s="hello";
String s2=s.substrig(0,3);***

so s2 will have "hel";

    public final class String_Test {

    String name;
    List<String> list=new ArrayList<String>();

    public static void main(String[] args) {

        String_Test obj=new String_Test();
        obj.list.add("item");//List will point to a memory unit- i.e will have one Hashcode value #1234

        List<String> list2=obj.list; //lis1 also will point to same #1234

        obj.list.add("new item");//Hashcode of list is not altered- List is mutable, so reference remains same, only value in that memory location changes

        String name2=obj.name="Myname"; // name2 and name will point to same instance of string -Hashcode #5678
        obj.name = "second name";// String is Immutable- New String HAI is created and name will point to this new instance- bcoz of this Hashcode changes here #0089

        System.out.println(obj.list.hashCode());
        System.out.println(list2.hashCode());
        System.out.println(list3.hashCode());

        System.out.println("===========");
        System.out.println(obj.name.hashCode());
        System.out.println(name2.hashCode());
    }
}

Will produce out put something like this

1419358369 1419358369

103056 65078777

Purpose of Immutable object is that its value should not be altered once assigned. It will return new object everytime you try to alter it based on the implementation. Note: Stringbuffer instead of string can be used to avoid this.

To your last question :: u will have one reference , and 2 strings in string pool.. Except the reference will point to m!ss!ss!pp!

Related