Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

boolean[][] grid = {{false,false}, {false,false}}; WorldState test1 = new WorldS

ID: 3545506 • Letter: B

Question

boolean[][]  grid = {{false,false},

{false,false}};

WorldState test1 = new WorldState(grid,0,0);

System.out.println(Arrays.deepToString(grid));


Why does the boolean value of the grid changes after I use in in the WorldState.  Shouldnt it stay false because I am not assigning anything to grid.  I The system prints out the grid and it is [[true, false], [false, false]].  I dont understand where the true is coming from.  please tell me why it is changing to true.  Thank you. Worlds state code below:


public class WorldState

{

boolean[][]grid2;

public WorldState(boolean[][] grid, int row, int col)

{

this.grid2=grid;

this.grid2[row][col] = true;

}

}

Explanation / Answer

The statement WorldState test1 = new WorldState(grid,0,0); creates an object of the Class WorldState and while doing so, it calls the constructor of the Class(Please note that whenever you create an object of a class using new, the constructor of the class is called). Now, in the constructor of the class, the statement this.grid2=grid; copies the grid object(2-d array) passed to it into the grid2 object. The important point to note is that in JAVA objects are passed by reference and assignments to objects are also references, therefore when the statement this.grid2[row][col] = true; is executed, the corresponding cell in the grid object also changes because this.grid2 is just a reference of grid object and any change to this.grid2 will be reflected into grid.

If you do not want to do this, then just copy the grid value by value(using loops) instead of assigning grid object directly.