Differentiating Array definitions

Arrays in Processing (and Java) are objects, which means that the variable only holds a reference. When you assign the array to a different variable, it does not create a copy of the array. Both variables will point to the same array. See this example:

int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

printArray(array1); // 1, 2, 3
printArray(array2); // 4, 5, 6

array1 = array2;
// now both variables refer to the same array

printArray(array1); // 4, 5, 6
printArray(array2); // 4, 5, 6

// there is now only one array, changes are
// visible through both variables (references)
array2[0] = 42;

printArray(array1); // 42, 5, 6
printArray(array2); // 42, 5, 6

array1 = array2.clone();
// now there are two separate arrays
array2[0] = 21;

printArray(array1); // 42, 5, 6
printArray(array2); // 21, 5, 6
2 Likes