Java - String and array references

前端 未结 4 1207
星月不相逢
星月不相逢 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:39

    First of all String is a immutable. Immutalbe means that you cannot change the object itself, but you can change the reference. Like in your case -

        String a = "a1"; // a is a reference variable and point to new object with value "a1"
    
        String b = "a2"; // b is a reference and point to new object with value "a2"
    
        a=b; // now a is referencing same object as b is referencing, a and b value is "a2"
    
        a = "rrr"; // at this time "rrr" is creating a new String object with value "rrr" and now a is pointing to this object.
    

    So b is still point to "a2" and now a is pointing to new object "rrr". That's why both print different value.

        System.out.println(a);
        System.out.println(b);
    

提交回复
热议问题