Java immutable strings confusion

后端 未结 8 1327
粉色の甜心
粉色の甜心 2021-01-13 03:07

If Strings are immutable in Java, then how can we write as:

String s = new String();
s = s + \"abc\";
8条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 03:46

    Immutable Classes are those whose methods can change their fields, for example:

    Foo f = new Foo("a");
    f.setField("b"); // Now, you are changing the field of class Foo
    

    but in immutable classes, e.g. String, you cannot change the object once you create it, but of course, you can reassign the reference to another object. For example:

    String s = "Hello";
    s.substring(0,1); // s is still "Hello"
    s = s.substring(0,1); // s is now referring to another object whose value is "H"
    

提交回复
热议问题