import java.util.Scanner; public class Driver { public static void main(String [] args) { Scanner in = new Scanner(System.in); int index; int age; // 1) Reference to array created // Reference is null Person [] aList; // 2) One-dimensional array with 3 elements created // Each array element is a reference to a Person object // Currently each array element is null aList = new Person[3]; // Creates a Person object, array element one now contains // the address of that object, the other elements in the array // are still null aList[1] = new Person(); // If the user tries to access element 0 or 2 a null pointer // exception resulting in a runtime error crashing the program will // be the result. System.out.print("Enter array element to access (hint only enter 1): "); index = in.nextInt(); System.out.print("Enter new age value for the person: "); age = in.nextInt(); // JT: Normally if accessing invalid indices is an issue then a check should // really be done: if (index != 1) then error // This was excluded for illustration purposes, there is only one object, one // array element (index 0) refers to it. The other array indices are still null! aList[index].setAge(age); System.out.println("Person #" + index + " is age: " + aList[index].getAge()); // To prove that the array elements are references to objects and not actual objects // here is a shallow copy (both assignments only copy the address of the object) aList[0] = aList[1]; aList[2] = aList[1]; // Not null anymore System.out.println("Person #0 is age: " + aList[0].getAge()); System.out.println("Person #2 is age: " + aList[2].getAge()); // Proof: 3 refences to the same object aList[0].setAge(-1999); for (index = 0; index < 3; index++) System.out.println("Person #" + index + " is age: " + aList[index].getAge()); } }