Here is a discussion of arrays of objects in Java.

Fix some class, for example

class Employee{ string name; int id;}

Now let's create an array of ten Employees:

Employee[] e = new Employee[10];

Do you think that you can now do

e[3].name = "Fred"; // you can't, you'll get a null pointer error.

What is the reason for this error? So far, you haven't actually created any Employee objects. The line containing "new" above created an array of ten references to Employee. By default those references are all null. You have an array containing ten null references. In particular e[3] is null so when you try to access e[3].name, it is an error.

To populate your array, do this:

for(int i = 0; i < e.length; e++)
  e[i] = new Employee();

This came up, for example, in the Google homework where you have to create an array of linked lists.

By contrast, if I create an array of ints, doubles, bytes, or chars, then my array does not contain references, but space for the actual data.

double[] x = new double[10];
   x[3] = 5.4; // no problem

But if I create an array of Integer instead of int, I will have the same problem as above, because Integer is a class, while int is a value type.

The general points here are

Another way of expressing this is: the value of a variable x is data, if x has a value type, or is a reference, if x has a class type. That "reference" is an address of the actual data, which occupies space originally created by 'new'. Before they have been initialized by 'new', references have the default value null.

A student raised this question: "Shouldn’t we consider class “String” as an exception? It looks like that it does not need to be initialized." I guess the student had in mind some code like this:

public class StringArrayTest {
   static String[] test;
   public static void main(String[] args)
       { test = new String[100];
         test[3] = "cat";
       }
}

This code does not throw any exception. So is it a counterexample to the information above? No. Up until the assignment statement in the last line of code, test[3] has the value null. (You can verify that by inserting System.out.println(test[3]); before the assignment statement.) No space for an object of type String has been allocated. So why, then does the assignment statement not throw an exception? Because the operator given by the = sign has been overloaded for the String class so that it calls a constructor. Thus what looks like an assignment statement really is equivalent to

test[3] = new String("cat");