Immutability of Strings in Java

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

    Light_handle I recommend you take a read of Cup Size -- a story about variables and Pass-by-Value Please (Cup Size continued). This will help a lot when reading the posts above.

    Have you read them? Yes. Good.

    String str = new String();
    

    This creates a new "remote control" called "str" and sets that to the value new String() (or "").

    e.g. in memory this creates:

    str --- > ""
    

    str  = "Hello";
    

    This then changes the remote control "str" but does not modify the original string "".

    e.g. in memory this creates:

    str -+   ""
         +-> "Hello"
    

    str = "Help!";
    

    This then changes the remote control "str" but does not modify the original string "" or the object that the remote control currently points to.

    e.g. in memory this creates:

    str -+   ""
         |   "Hello"
         +-> "Help!"
    

提交回复
热议问题