Java - String and array references

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

    In the array case, you're actually modifying the array, and thus if one reference is changed, so is the other.

    In the string case, you are not modifying the object, you are simply assigning a different object to that reference. As you noted: a=b means "let a point to the same object as b is pointing". Following the same line of thought, a="rrr" means "let a point to the literal "rrr"", which has nothing to do with with b.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

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