6.5 Arrays: Declaration, Initialization, Multidimensional Arrays, and the Arrays Utility Class

Key Takeaways

  • In the declaration int c[], d; only c is an array and d is a plain int, while int[] a, b; declares two arrays.

  • Array elements default to 0, false, '\u0000', or null, and length is a field rather than a method.

  • Arrays.binarySearch on a sorted array returns the index or -(insertion point) - 1, and its result is undefined for unsorted input.

  • Arrays.mismatch returns the first differing index or -1, while Arrays.compare orders arrays element by element with shorter prefixes first.

  • Arrays do not override equals or toString, so use Arrays.equals, Arrays.toString, and Arrays.deepToString to compare and print contents.

Last updated: October 2026

6.5 Arrays: Declaration, Initialization, Multidimensional Arrays, and the Arrays Utility Class

The collections objective begins with "Create Java arrays", and arrays also sit underneath varargs, main(String[] args), and Stream.toArray. Array questions test declaration syntax, default values, exceptions, and the exact return values of the java.util.Arrays helper methods.


Declaring and Creating Arrays

An array is an object with a fixed length that holds elements of one type. The brackets may follow the type or the variable name, and that choice changes multi-variable declarations:

int[] a, b;      // a and b are both int[]
int c[], d;      // c is int[], but d is a plain int!
int[] e, f[];    // e is int[], f is int[][]

Creation rules:

CodeResult
int[] nums = new int[3];Three elements, each 0
int[] nums = new int[] {1, 2, 3};Size inferred from the initializer
int[] nums = {1, 2, 3};Shorthand, allowed only in a declaration
int[] bad = new int[3] {1, 2, 3};Compile error: size and initializer together
int[] none = new int[0];Legal empty array (length is 0)
int[] neg = new int[-1];Compiles, throws NegativeArraySizeException at runtime

Elements receive the same defaults as fields: 0 for numeric types, false for boolean, '\u0000' for char, and null for references. Arrays.toString(new String[2]) prints [null, null].

  • length is a field (nums.length), while String uses the method length().
  • Valid indexes run from 0 to length - 1; anything else throws ArrayIndexOutOfBoundsException at runtime.
  • An array reference prints like [I@1b6d3586 because arrays do not override toString(); use Arrays.toString(arr).
  • Arrays do not override equals() either: new int[] {1}.equals(new int[] {1}) is false, while Arrays.equals(...) compares contents and returns true.

Multidimensional and Jagged Arrays

Java has arrays of arrays. Each row is its own array object, so rows can have different lengths:

int[][] grid = new int[2][3];          // 2 rows, each an int[3] of zeros
int[][] jagged = {{1}, {2, 3}, {}};     // row lengths 1, 2, and 0
int[][] partial = new int[3][];         // rows not created yet
System.out.println(grid.length);        // 2  (number of rows)
System.out.println(grid[0].length);     // 3
System.out.println(partial[0]);         // null
System.out.println(Arrays.deepToString(jagged)); // [[1], [2, 3], []]
// int[][] wrong = new int[][3];        // Compile error: the first dimension is required

Use nested loops (or for (int[] row : grid)) to traverse rows and columns, and Arrays.deepToString to print nested arrays.


The java.util.Arrays Utility Class

MethodExampleResult
sort(arr)String[] s = {"b", "A", "a", "10", "9"};[10, 9, A, a, b] (digits before uppercase before lowercase)
sort(arr, comparator)Arrays.sort(boxed, Comparator.reverseOrder())Works only on object arrays such as Integer[], not int[]
binarySearch(arr, key)binarySearch(new int[] {2, 4, 6, 8}, 6)2 (the index)
binarySearch (key absent)binarySearch(new int[] {2, 4, 6, 8}, 5)-3, computed as -(insertion point) - 1
equals(a, b)equals(new int[] {1}, new int[] {1})true
compare(a, b)compare(new int[] {1, 2}, new int[] {1, 2, 3})Negative: equal prefix, so the shorter array is smaller
mismatch(a, b)mismatch(new int[] {1, 2, 3}, new int[] {1, 2, 4})2 (first differing index), or -1 if equal
fill(arr, v)fill(new int[3], 7)[7, 7, 7]
copyOf(arr, n)copyOf(new int[] {1, 2, 3}, 5)[1, 2, 3, 0, 0] (pads or truncates)
copyOfRange(arr, from, to)copyOfRange(new int[] {1, 2, 3, 4}, 1, 3)[2, 3] (end exclusive)
asList(...)Arrays.asList("x", "y")Fixed-size list backed by the array (see 6.3)
stream(arr)Arrays.stream(new int[] {1, 2})An IntStream (see 8.1)

Warning

binarySearch requires a sorted array. On an unsorted array the result is undefined, so exam answers such as "the result cannot be predicted" are correct for unsorted input. For a missing key, compute the insertion point first: in {2, 4, 6, 8}, the key 5 belongs at index 2, so the result is -(2) - 1 = -3; the key 1 gives -1, and the key 9 gives -5.

compare versus mismatch

Arrays.compare returns an int like compareTo: it compares elements in order, and if one array is a prefix of the other, the shorter array is smaller. Arrays.compare(new int[] {1, 3}, new int[] {1, 2, 9}) is positive because 3 > 2 at index 1, even though the first array is shorter. Arrays.mismatch instead returns the first index where the arrays differ: mismatch(new int[] {1, 2}, new int[] {1, 2, 3}) is 2 (the length of the shorter array), and identical arrays give -1.


Arrays, Varargs, and Covariance

  • A varargs parameter (String... names) is an array inside the method, and callers may pass an existing array (see 3.1).
  • Arrays are covariant: a String[] can be assigned to an Object[] variable, but storing an Integer into it throws ArrayStoreException at runtime (see 6.2).
  • arr.clone() creates a new array with the same elements; for arrays of objects, the elements themselves are shared (a shallow copy).
Test Your Knowledge

What does the following code print?

int[] data = {8, 2, 6, 4};
Arrays.sort(data);
System.out.print(Arrays.binarySearch(data, 6) + " ");
System.out.print(Arrays.binarySearch(data, 5));
A

1 -3

B

2 -3

C

2 -2

D

2 -1

Test Your Knowledge

Given the declarations below, which statement compiles?

int[] a, b;
int c[], d;
A

a = c; d = c.length;

B

b = 5;

C

c = d; b = new int[d];

D

d = new int[] {1, 2, 3};

Test Your Knowledge

What is the output of this code?

int[] x = {1, 2, 3};
int[] y = {1, 2, 4, 5};
System.out.print(Arrays.mismatch(x, y) + " ");
System.out.print(Arrays.compare(x, y) < 0);
System.out.print(" " + x.equals(new int[] {1, 2, 3}));
A

2 true false

B

2 false false

C

-1 true true

D

3 true false

Sections you finish are checked off in the contents.