Advertisement
Beginner Java, Arrays & Multidimensional Arrays

How do you declare and initialize an array of objects (reference types) versus an array of primitives, and what is the key difference in their default values?

Short answer

An array of primitives (int[], double[]) has elements automatically initialized to their type's zero-equivalent default (0, 0.0, false), while an array of reference types (String[], custom objects) has every element initialized to null by default, since no object instance is…

Save Java mock interview
Advertisement
AModel answer
An array of primitives (int[], double[]) has elements automatically initialized to their type's zero-equivalent default (0, 0.0, false), while an array of reference types (String[], custom objects) has every element initialized to null by default, since no object instance is automatically created -- attempting to call a method on an uninitialized reference-type array element before explicitly assigning it throws a NullPointerException.
int[] nums = new int[3];        // {0, 0, 0}
boolean[] flags = new boolean[3];  // {false, false, false}
String[] names = new String[3];    // {null, null, null}

System.out.println(names[0].length());  // throws NullPointerException, since names[0] is null
Real-world example
A beginner's attempt to call .length() on an element of a freshly created String[] array (without first assigning actual String values to each slot) throws a NullPointerException, a common early mistake stemming from not realizing reference-type arrays default to null rather than empty strings.
Likely follow-ups
  • Why don't reference-type arrays default to an empty object instance instead of null?
  • How would you safely initialize every element of an object array to a non-null default value?
Related topics