Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8): Creating and Using Arrays

Java SE 8 Programmer I (OCAJP 8) · Work through your exam, one topic at a time.

All guide sections

Creating and Using Arrays

Creating and Using Arrays

This domain tests declaration, instantiation, initialization, indexing, and multidimensional arrays. Arrays are fixed-size objects, and most exam errors are compile-time declaration mistakes or runtime bounds/null failures.

Declarations and creation

  • int[] a; and int a[]; both declare an array reference; neither allocates an array, and no size may appear in the declaration brackets.
  • new int[3] allocates three elements with default values: 0, false, or null.
  • An initializer may appear only with a declaration or an array creation expression: int[] a = {1,2}; or int[] b = new int[]{1,2};.
  • length is a field, not a method. Valid indexes are 0 through length - 1; outside that range throws ArrayIndexOutOfBoundsException.
  • Multidimensional arrays are arrays of arrays and may be ragged. new int[2][] creates two null row references; each row must be allocated separately.

Worked example

int[] nums = {3, 1, 2};
int[] alias = nums;
alias[0] = 9;
System.out.println(nums[0]);

Both variables refer to the same array object, so the update through alias is visible through nums; the output is 9. Passing an array to a method works the same way: the method receives a copy of the reference.

Traps

  • a.length() does not exist for arrays; use a.length.
  • Accessing a[a.length] is always out of bounds.
  • A String[] is an Object[], but storing a non-String into it through an Object[] reference throws ArrayStoreException.
  • A jagged array element may be null; dereferencing it throws NullPointerException before any index check.
  • Reassigning a method parameter that holds an array does not change the caller's reference.