String object is immutable but reference variable is mutable. What does that mean?

后端 未结 2 1015
别那么骄傲
别那么骄傲 2020-12-12 03:23

I was studying Kathy Sierra Java book. I came across one question something like this:

public class A {
    public static void main(String args[]){
        S         


        
2条回答
  •  心在旅途
    2020-12-12 03:38

    s2 is a reference to s1 in the first case. In the second case, + is translated to s1.concat("d") which creates a new string, so the references s1 and s2 point to different string objects.

    In the case of StringBuffer, the reference never changes. append changes the internal structure of the buffer, not the reference to it.

提交回复
热议问题