Immutability of Strings in Java

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

    String is immutable means that you cannot change the object itself, but you can change the reference to the object. When you called a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty". Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:

    Foo x = new Foo("the field");
    x.setField("a new field");
    System.out.println(x.getField()); // prints "a new field"
    

    While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:

    String s = "some text";
    s.substring(0,4);
    System.out.println(s); // still printing "some text"
    String a = s.substring(0,4);
    System.out.println(a); // prints "some"
    

提交回复
热议问题