Java immutable strings confusion

后端 未结 8 1321
粉色の甜心
粉色の甜心 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:43

    I believe you are all making this much more complicated than it needs to be, and that simply confuses people who are trying to learn!

    The primary benefit of making an object immutable in Java is that it can be passed by reference (e.g. to another method or assigned using the assignment operator) without having to worry about downstream changes to the object causing issues in the current method or context. (This is very different than any conversation about the thread safety of an object.)

    To illustrate, create an application that passes a String as a parameter to a separate method, and modify the String in that method. Print the String at the end of the called method and then after control returns to the calling method. The Strings will have different values, and that's because they point to different memory locations, a direct result of "changing" the immutable String (creating a new pointer and pointing it to a new value behind the scenes). Then create an application that does the same things except with StringBuffer, which is not immutable. (For example, you can append to the StringBuffer to modify it.) The printed StringBuffers will have the same values, and that is because it is (a) being passed by reference, as Java does with all objects passed to methods as parameters and (b) mutable.

    I hope this helps folks who are reading this thread and trying to learn!

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题