I read somewhere that System.arraycopy
does create a new copy for primitive data types and shallow copy for object references.
so, that I started the experiment that with below code
//trying with primitive values
int a[] ={1,2,3};
int b[] = new int[a.length];
System.arraycopy(a,0,b,0,a.length);
b[0] = 9;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
//now trying with object references
Object[] obj1 = {new Integer(3),new StringBuffer("hello")};
Object[] obj2 = new Object[obj1.length];
System.arraycopy(obj1,0,obj2,0,obj1.length);
obj1[1] = new StringBuffer("world");
System.out.println(Arrays.toString(obj1));
System.out.println(Arrays.toString(obj2));
and the output was
[1, 2, 3]
[9, 2, 3]
[3, world]
[3, hello]
But what I expected was
[1, 2, 3]
[9, 2, 3]
[3, world]
[3, world]
from the above code, I understood that System.arraycopy
does deep copy for object references
If so, how obj1[0] == obj2[0]
gives true