Immutability of Strings in Java

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

    If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

    You can have multiple pointer String variable to point HELLO String.

    But if HELLO is char Array then you can change HELLO to HILLO. Eg,

    char[] charArr = 'HELLO';
    char[1] = 'I'; //you can do this
    

    Programming languages have immutable data variables so that it can be used as keys in key, value pair.

提交回复
热议问题