Lecture 8 II: Arrays

2 different ways to create an array of objects

public class ArrayTest{
    public static void main(String[] args) {
        BankAccount[] array = {new BankAccount("Amy", 1000),
	                       new BankAccount("Ben", 23456),
                                new BankAccount("Charles", 521)};
	for(int i = 0; i < array.length; i++) {
	    System.out.println(array[i].getName() + " has $" + array[i].getSaving() + ".");
	}
    }
}
is same as
public class ArrayTest{
    public static void main(String[] args) {
        BankAccount[] array = new BankAccount[3];
	array[0] = new BankAccount("Amy", 1000);
	array[1] = new BankAccount("Ben", 23456);
	array[2] = new BankAccount("Charles", 521);
	for(int i = 0; i < array.length; i++) {
	    System.out.println(array[i].getName() + " has $" + array[i].getSaving() + ".");
	}
    }
}
The output is
Amy has $1000.
Ben has $23456.
Charles has $521.

null

What is the output of the following program?
public class ArrayTest{
    public static void main(String[] args) {
        BankAccount[] array = new BankAccount[3];
	array[0] = new BankAccount("Amy", 1000);
	array[1] = new BankAccount("Ben", 23456);
	//array[2] = new BankAccount("Charles", 521);  
	for(int i = 0; i < array.length; i++) {
	    System.out.println(array[i].getName() + " has $" + array[i].getSaving() + ".");
	}
    }
}
Output
Exception in thread "main" java.lang.NullPointerException
        at ArrayTest.main(ArrayTest.java:8)
Explanation:
null is a keyword in Java.
public class ArrayTest{
    public static void main(String[] args) {
        BankAccount[] array = new BankAccount[3];
	array[0] = new BankAccount("Amy", 1000);
	array[1] = new BankAccount("Ben", 23456);
	//array[2] = new BankAccount("Charles", 521);
	for(int i = 0; i < array.length; i++) {
	    if(array[i] == null) {
		System.out.println("array[" + i +"] is null.");
	    } else {
	         System.out.println(array[i].getName() + 
		 " has $" + array[i].getSaving() + ".");
	    }
	}
    }
}
Output:
Amy has $1000.
Ben has $23456.
array[2] is null.

Out of bound

public class ArrayTest{
    public static void main(String[] args) {
        BankAccount[] array = {new BankAccount("Amy", 1000),
	                       new BankAccount("Ben", 23456),
                                new BankAccount("Charles", 521)};
	int num = 4;
	for(int i = 0; i < num; i++) {
	    System.out.println(array[i].getName() + " has $" + array[i].getSaving() + ".");
	}
    }
}
Output
Amy has $1000.
Ben has $23456.
Charles has $521.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
        at ArrayTest.main(ArrayTest.java:8)