-1

I started to learn JAVA and am trying to understand something about arrays. So within the code below, the elements of arr1 has been assigned to arr2[1] and in the second loop, arr2[row][col] was incremented.

I was just monkeying around with debugger and realized that the content of arr1 has also been incremented along with arr2[row][col].

It might be a dummy question but I really could not understand it, can you elaborate the logic there please?

public static void main(String[] args){

    int[] arr1 = { 1, 2, 3, 4};
    int[][] arr2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    arr2[1] = arr1;
    for (int row = 0; row < arr2.length; row++) {
        for (int col = 0; col < arr2[row].length; col++){
            System.out.print( arr2[row][col] + " " );
            arr2[row][col]++;
        }
        System.out.println("");
    }
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Benjamin Park
  • 41
  • 1
  • 1
  • 5

3 Answers3

1

arr2[1] is a reference to arr1 So, when you increment a number in arr2[1], it also reflects in arr1.

Java object variables are references, so arr2[1] simply points to the same address as arr1. You can find many articles on this:

Your code, declares an array:

int[] arr1 = {1, 2, 3, 4}; 

declares an multidimensional array (array of array):

int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

assigns the arr2's second array (ie: arr2[1]) to arr1:

arr2[1] = arr1; // {1, 2, 3, 4}
Community
  • 1
  • 1
alexbt
  • 16,415
  • 6
  • 78
  • 87
  • I definitely got that part. My question is, why all the elements of `arr1` get incremented as the program executes `arr2[row][col]++;` each time? – Benjamin Park Jun 13 '16 at 15:39
  • see my edit, I think the answer is there now (the very first line) – alexbt Jun 13 '16 at 15:40
1

Here

int[] arr1 = { 1, 2, 3, 4};
int[][] arr2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
arr2[1] = arr1;

you are changing the 2nd element of arr2 for the the value of arr1 so

arr2 = { {1, 2, 3}, { 1, 2, 3, 4}, {7, 8, 9} };

is correct!

and in the second loop, arr2[row][col] was incremented.

yes you increment those, but the result of that operation is not getting assigned to anything so, those changes are getting lost...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You are setting arr2[1] referencing the variable arr1. So, when you modify arr2[1] you are modifying the value of arr1 really.

If you want to set to arr2[1] the value of arr1, use this:

arr2[1] = arr1.clone();

The method clone returns a value, not a reference.

Hope this helps. Regards.

Carlos Durán
  • 186
  • 10