Immutability of Strings in Java

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

    In Java, objects are generally accessed by references. In your piece of code str is a reference which is first assigned to "Hello" (an automatic created object or fetched from constant pool) and then you assigned another object "Help!" to same reference. A point to note is the reference is the same and modified, but objects are different. One more thing in your code you accessed three objects,

    1. When you called new String().
    2. When you assigned "hello".
    3. When you assigned "help!".

    Calling new String() creates a new object even if it exists in string pool, so generally it should not be used. To put a string created from new String () into string pool you can try the intern() method.

    I hope this helps.

提交回复
热议问题