Search code examples
javapass-by-referencepass-by-value

If arrays are object in java why the assignment between arrays is deep copy


If arrays are object as stated in Is an array an object in java then why the output of the code snipped below is [1,1,1]?

I thought after the execution of statement "a=b;" a and b are still pointing to the same content! Isn't it supposed to be shadow copy between objects?

import java.util.Arrays;

public class Local {
    int [] a = null;
    public Local(){
    int [] b = {1,1,1};
    int [] c = {5,5};
    a=b;
    b=c;// 'a' should change too as a and b are both objects! right?
    }

    public static void main(String[] args) {
        Local local = new Local();
        System.out.println(Arrays.toString(local.a));
    }

}

Solution

  • Let me try to explain it line per line:

    int [] b = {1,1,1};
    

    enter image description here

    On this line, three things happened.

    1. Created a variable named b.
    2. Created an array of int {1,1,1}
    3. Assigned b to the array of intcreated on step 2.

    int [] c = {5,5};

    enter image description here

    Same thing happened here

    1. Created a variable named c.
    2. Created an array of int {5,5}
    3. Assigned c to the array of int created on step 2.

    a=b;

    Now we also assigned a to whatever the value of b is, which in this case is the array of int {1,1,1}

    Now we have something like

    enter image description here

    b=c; // 'a' should change too as a and b are both objects! right?
    

    What happened here is that we assigned b to whatever c's value is (int array {5,5}), now b is not pointing to {1,1,1} anymore and since Java is pass by value, a's value remained. It's not like a is pointing to the reference of b that whatever b is pointing to, a will point to it too.

    enter image description here

    Hope this helps.