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));
}
}
Let me try to explain it line per line:
int [] b = {1,1,1};
On this line, three things happened.
b
.int
{1,1,1}
b
to the array of int
created on step 2.int [] c = {5,5};
Same thing happened here
c
.int
{5,5}
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
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.
Hope this helps.