All arrays in Java are objects, regardless of the types of values inside. A variable of array type stores the memory address of the array, just as with any other object.
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 (this resource)
- Arrays of objects exercises
- Enhanced for loop exercises (including with 2D arrays)
The exercises below use the same Coordinate2D
class as the 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: Array of primitives
public static void main(String[] args)
{
int[] nums = new int[] {1, 2, 3};
System.out.println(Arrays.toString(nums));
// prints: [1, 2, 3]
mystery1(nums);
System.out.println(Arrays.toString(nums));
}
public static void mystery1(int[] arr)
{
arr[0] = 4;
}
What is printed by the 2nd print statement in the code above?
Exercise 1 solution & explanation
Exercise 2: Another array of primitives
public static void main(String[] args)
{
int[] nums = new int[] {1, 2, 3};
System.out.println(Arrays.toString(nums));
// prints: [1, 2, 3]
mystery2(nums);
System.out.println(Arrays.toString(nums));
}
public static void mystery2(int[] arr)
{
arr = new int[3];
arr[0] = 5;
}
What is printed by the 2nd print statement in the code above?
Exercise 2 solution & explanation
Exercise 3: Array of objects
public static void main(String[] args)
{
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)]
mystery3(coors);
System.out.println(Arrays.toString(coors));
}
public static void mystery3(Coordinate2D[] coorsInside)
{
coorsInside[0] = new Coordinate2D(4, 4);
}
What is printed by the 2nd print statement in the code above?
Exercise 3 solution & explanation
Exercise 4: Another array of objects
public static void main(String[] args)
{
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)]
mystery4(coors);
System.out.println(Arrays.toString(coors));
}
public static void mystery4(Coordinate2D[] coorsInside)
{
coorsInside = new Coordinate2D[3];
coorsInside[0] = new Coordinate2D(5, 5);
}
What is printed by the 2nd print statement in the code above?
Exercise 4 solution & explanation
Help & comments
Get help from AP CS Tutor Brandon Horn