Java variable is changing without assignment

  • A+
Category:Languages

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]; } 

 


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].

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: