Java variable is changing without assignment

Viewed 756

I don't understand why the variable initialCoordinates is changing. When I run the program, initialCoordinates changes values after each run of the loop.

int[] initialCoordinates = { 26, 0 };
int[] positions = { 1, 2, 3, 4 };
int[][] coordinates = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
for (int i = 0; i < 4; i++) {
    System.out.println("Initial: " + initialCoordinates[1]);
    coordinates[i] = initialCoordinates;
    coordinates[i][1] += positions[i];
}
3 Answers

In your example you're setting coordinates[i] to initialCoordinates.

Then in the next line you're executing coordinates[i][1] = ..., that's when you're accesing initialCoordinates indirectly through coordinates[i] and changing the the value of initialCoordinates[1].

As Mark said, you are accessing initialCoordinates with the coordinates variable because you assigned it by reference. This means that after coordinates [i]=initialCoordinates;, coordinates[i] will then reference the same memory address that initalCoordinates does so that when one changes the other changes also.

What you probably wanted to do is copy the values which would have the effect of assigning it by value. You can do that using System.arraycopy (See this answer). By assigning by value, you allocate a separate chunk of memory to hold the values for coordinates[i] which will be copied from initialCoordinates rather than having both variables pointing to the same thing in memory.

int [] initialCoordinates = {26,0};
int [] positions={1,2,3,4};
int [][] coordinates = {{0,0},{0,0},{0,0},{0,0}};
for(int i=0;i<4;i++){
    System.out.println("Initial: "+initialCoordinates[1]);
    System.arraycopy(initialCoordinates, 0, coordinates[i], 0, initialCoordinates.length);
    coordinates [i][1]+=positions[i];
}

I will attempt to show you, what is approximately going on in java memory.

  • first you created instances in the stack, which points to objects in the heap

enter image description here

  • then you changed the pointer of coordinates[0], and both variables - initialCoordinates and coordinates[i] point to the same object in the heap

  • so, when you changed coordinates[0], you also changed the object in the heap. The initialCoordinates also refers to object in the heap, so intialCoordinates were also "changed"..

enter image description here

Related