Immutability of Strings in Java

后端 未结 26 2312
不思量自难忘°
不思量自难忘° 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:33

    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.

提交回复
热议问题