Immutability of Strings in Java

后端 未结 26 2382
不思量自难忘°
不思量自难忘° 2020-11-21 06:33

Consider the following example.

String str = new String();

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

str = \"Help!\";
System.out.println(s         


        
26条回答
  •  后悔当初
    2020-11-21 07:19

        public final class String_Test {
    
        String name;
        List list=new ArrayList();
    
        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 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!

提交回复
热议问题