Immutability of Strings in Java

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

提交回复
热议问题