Java - String and array references

前端 未结 4 1159
星月不相逢
星月不相逢 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条回答
  •  -上瘾入骨i
    2021-01-22 18:35

    You have 3 string objects and 1 array object.
    "a1", "a2", "rrr"
    {1,2,3}

    String a = "a1"; // a points to a new object "a1"
    String b = "a2"; // b points to a new object "a2"
    a=b; // a points to b's object "a2"
    a = "rrr"; // a points to new object "rrr"
    
    System.out.println(a); // prints "rrr" to console
    System.out.println(b); // Prints "a2" to console
    
    int[] arr1 = {1,2,3}; // arr1 points to new array {1,2,3}
    int[] arr2 = arr1; // arr2 points to array in arr1 {1,2,3}
    arr2[0]= 19; // modifies the array arr2 points to {19, 2, 3}
    System.out.println(arr1[0]); // Prints "19" to console
    

提交回复
热议问题