Immutability of Strings in Java

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

    Super late to the answer, but wanted to put a concise message from author of the String class in Java

    Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

    It can be derived from this documentation that anything that changes string, returns different object (which could be new or interned and old). The not so subtle hint about this should come from the function signature. Think about it, 'Why did they make a function on an object return an object instead of status?'.

    public String replace(char oldChar, char newChar) 
    

    Also one more source which makes this behaviour explicit (From replace function documentation)

    Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

    Source: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)

    • author Lee Boynton
    • author Arthur van Hoff
    • author Martin Buchholz
    • author Ulf Zibis

    Source: JavaDoc of String.

提交回复
热议问题