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.
- Primitive types vs references exercises
- Primitive types vs references exercises with calls
- Arrays as objects exercises
- Arrays of objects exercises (this resource)
- Enhanced for loop exercises (including with 2D arrays)
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[3];
coors[0] = new Coordinate2D(1, 1);
coors[1] = new Coordinate2D(2, 2);
coors[2] = new Coordinate2D(3, 3);
System.out.println(Arrays.toString(coors));
// prints: [(1, 1), (2, 2), (3, 3)]
Coordinate2D[] coors2 = new Coordinate2D[3];
for(int i = 0; i < coors2.length; i++)
coors2[i] = coors[i];
coors2[0] = new Coordinate2D(4, 4);
coors2[1].setX(5);
coors2[1].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[3];
coors[0] = new Coordinate2D(1, 1);
coors[1] = new Coordinate2D(2, 2);
coors[2] = new Coordinate2D(3, 3);
System.out.println(Arrays.toString(coors));
// prints: [(1, 1), (2, 2), (3, 3)]
Coordinate2D[] coors2 = new Coordinate2D[3];
for(int i = 0; i < coors2.length; i++)
coors2[i] = new Coordinate2D(coors[i].getX(), coors[i].getY());
coors2[0] = new Coordinate2D(4, 4);
coors2[1].setX(5);
coors2[1].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
This exercise uses a 2D array. See Intro to 2D arrays for details of 2D arrays in Java.
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[1];
row[0] = 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.
Help & comments
Get help from AP CS Tutor Brandon Horn