Java - String and array references

前端 未结 4 1165
星月不相逢
星月不相逢 2021-01-22 18:15

Just started to learn Java, and saw that both string and array are reference types. I don\'t understand the following issue:

    String a = \"a1\";
    String b          


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-22 18:36

    So, reassignment is a different thing from modification.

    If you have

    String a = "foo";
    String b = a;
    

    then you have assigned b to refer to the same object as a. If you then do

    b = "bananas";
    

    then you haven't modified the string, you have reassigned b so it is no longer referring to the same object as a.

    On the other hand

    int[] c = { 1, 2, 3 };
    int[] d = c;
    

    Here again we have d assigned to refer to the same object (an array) as c. If you then do something like this:

    d[0] = 10;
    

    then you are modifying the contents of the array that both c and d refer to.

提交回复
热议问题