# Arrays of objects exercises

These exercises demonstrate how arrays of objects in Java are actually arrays of references (memory addresses).

These exercises are part of a collection intended to be covered in the order below.

The exercises below use the same `Coordinate2D` class the other resources above.

Note: `Arrays.toString` returns a formatted `String` containing the values in its array parameter. In the case of an array of objects, the `toString` method of each object is run. `Arrays.toString` is not part of the AP CS A Java Subset.

## Exercise 1: Shallow copy

``````Coordinate2D[] coors = new Coordinate2D;
coors = new Coordinate2D(1, 1);
coors = new Coordinate2D(2, 2);
coors = new Coordinate2D(3, 3);

System.out.println(Arrays.toString(coors));
// prints: [(1, 1), (2, 2), (3, 3)]

Coordinate2D[] coors2 = new Coordinate2D;

for(int i = 0; i < coors2.length; i++)
coors2[i] = coors[i];

coors2 = new Coordinate2D(4, 4);

coors2.setX(5);
coors2.setY(5);

System.out.println(Arrays.toString(coors));

System.out.println(Arrays.toString(coors2));
``````

What is printed by the last 2 print statements in the code above?

Exercise 1 solution & explanation

## Exercise 2: Deep copy

``````Coordinate2D[] coors = new Coordinate2D;
coors = new Coordinate2D(1, 1);
coors = new Coordinate2D(2, 2);
coors = new Coordinate2D(3, 3);

System.out.println(Arrays.toString(coors));
// prints: [(1, 1), (2, 2), (3, 3)]

Coordinate2D[] coors2 = new Coordinate2D;

for(int i = 0; i < coors2.length; i++)
coors2[i] = new Coordinate2D(coors[i].getX(), coors[i].getY());

coors2 = new Coordinate2D(4, 4);

coors2.setX(5);
coors2.setY(5);

System.out.println(Arrays.toString(coors));

System.out.println(Arrays.toString(coors2));
``````

What is printed by the last 2 print statements in the code above?

Exercise 2 solution & explanation

## Exercise 3: Row in 2D array

`Arrays.deepToString` is a method to quickly produce formatted output. It is not covered on the AP CS A Exam. The format of the output below has been adjusted for readability.

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

System.out.println(Arrays.deepToString(mat));
// prints:
// [[1, 2, 3],
//  [4, 5, 6],
//  [7, 8, 9]]

int[] row = mat;

row = 0;

System.out.println(Arrays.deepToString(mat));
``````

What is printed by the 2nd print statement in the code above?

Exercise 3 solution & explanation

The first two 2D array exercises, `rowSwap` and `colSwap`, are relevant to this exercise.