Immutability of Strings in Java

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

    Immutability I can say is that you cannot change the String itself. Suppose you have String x, the value of which is "abc". Now you cannot change the String, that is, you cannot change any character/s in "abc".

    If you have to change any character/s in the String, you can use a character array and mutate it or use StringBuilder.

    String x = "abc";
    x = "pot";
    x = x + "hj";
    x = x.substring(3);
    System.out.println(x);
    
    char x1[] = x.toCharArray();
    x1[0] = 's';
    String y = new String(x1);
    System.out.println(y);
    

    Output:

    hj
    sj
    

提交回复
热议问题