Immutability of Strings in Java

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

    I would explain it with simple example


    consider any character array : e.g. char a[]={'h','e','l','l','o'}; and a string : String s="hello";


    on character array we can perform operations like printing only last three letters using iterating the array; but in string we have to make new String object and copy required substring and its address will be in new string object.

    e.g.

    ***String s="hello";
    String s2=s.substrig(0,3);***
    

    so s2 will have "hel";

    0 讨论(0)
  • 2020-11-21 07:39

    The object that str references can change, but the actual String objects themselves cannot.

    The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable.

    The immutability of String objects does not mean that the references pointing to the object cannot change.

    One way that one can prevent the str reference from changing is to declare it as final:

    final String STR = "Hello";
    

    Now, trying to assign another String to STR will cause a compile error.

    0 讨论(0)
提交回复
热议问题