6.3 Array Reference Behavior & java.util.Arrays Helpers

Key Takeaways

  • An array is an object. Its inherited equals tests reference identity, and its inherited toString includes the type name and a hash code.

  • Primitive arrays are invariant (int[] cannot be assigned to long[] or double[]), whereas reference-type arrays are covariant (String[] assigns to Object[]).

  • Writing a mismatched object type such as Integer into an Object[] reference backed by a String[] compiles cleanly and throws ArrayStoreException at runtime.

  • Arrays.sort sorts in place. Use natural ordering for String, where comparison uses UTF-16 code units. Incomparable object elements can cause ClassCastException.

  • On a correctly sorted array, Arrays.binarySearch returns a matching index or -insertionPoint - 1. The API leaves the result undefined if the array is unsorted.

Last updated: November 2026

Array Reference Behavior & java.util.Arrays Helpers

Because arrays are full-fledged objects in Java SE 8, understanding how array references behave under inheritance, assignment, method calls, and Object methods prevents some of the trickiest bugs on the exam.

Arrays as Objects on the Heap

Every array — even an array of primitives such as new int[0] — is an object whose direct superclass is java.lang.Object and which implements Cloneable and java.io.Serializable:

int[] nums = {1, 2, 3};
System.out.println(nums instanceof Object); // true

However, array classes do not override equals() or toString() from Object. Calling those methods directly on an array rarely produces what beginners expect:

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};

System.out.println(a == b);       // false (different heap objects)
System.out.println(a.equals(b));  // false! Object.equals uses == (reference identity)
System.out.println(a.toString()); // Prints something like [I@15db9742

In the array class name returned by Class.getName(), [I indicates a 1D int array, [[I indicates a 2D int array, and [Ljava.lang.String; indicates a 1D String array. To compare contents or print elements cleanly, use java.util.Arrays helpers (Arrays.equals(a, b) and Arrays.toString(a)).

Primitive Array Invariance vs. Reference Array Covariance

A single int widens automatically to long or double, which misleads many developers into thinking int[] can be assigned to long[]. In Java, primitive arrays are strictly invariant — there is no subtype relationship between int[] and long[]. The language’s array subtyping rules do not apply primitive widening to component types. For comparison, int[][] is assignable to Object[] because each int[] row is itself an object.

By contrast, reference-type arrays are covariant: if Sub is a subtype of Super, then Sub[] is a subtype of Super[]. Thus String[] can be assigned to Object[] or CharSequence[].

AssignmentCompiles?Why
Object o = new int[]{1, 2};YesEvery array (even primitive) is an Object
Object[] oa = new int[]{1, 2};Noint is not a reference type, so int[] is not an Object[]
long[] ls = new int[]{1, 2};NoPrimitive arrays are invariant (int[] is not a long[])
Object[] objs = new String[]{"a"};YesReference arrays are covariant (String extends Object)
CharSequence[] cs = new String[]{"a"};YesString implements CharSequence

Array covariance introduces a famous runtime hazard: ArrayStoreException. When a String[] object is accessed through an Object[] variable, the compiler permits storing any Object (such as an autoboxed Integer), because the compile-time type of the variable is Object[]. At runtime, the JVM checks the actual heap object's element type (String) and rejects the incompatible write:

String[] words = new String[2];
Object[] refs = words;           // Compiles: String[] is a subtype of Object[]
refs[0] = "hello";               // OK at runtime
refs[1] = 42;                    // Compiles (autoboxes to Integer), throws ArrayStoreException!
// In a separate run, refs[1] = null is legal because String is a reference type.

Passing Arrays to Methods

Java passes all arguments by value, which for an array means passing a copy of the array reference:

static void tweak(int[] arr) {
    arr[0] = 99;           // Mutates the caller's heap array
    arr = new int[]{7, 8}; // Reassigns only the local parameter 'arr'
}

public static void main(String[] args) {
    int[] data = {1, 2};
    tweak(data);
    System.out.println(data[0] + " " + data.length); // Prints: 99 2
}

The mutation arr[0] = 99 updates the shared heap object visible through data, whereas arr = new int[]{7, 8} points only the local parameter at a new object without altering data.

java.util.Arrays Helper Methods

The Arrays utility class lives in java.util (not java.lang), so use an import such as import java.util.Arrays; or the qualified name java.util.Arrays. Three core methods appear constantly in Java SE 8 code:

1. Arrays.toString(arr)

Formats a 1D array into a bracketed, comma-and-space-separated String ("[1, 2, 3]", "[]" for empty, or "null" if the array reference itself is null). For multidimensional arrays, Arrays.toString(grid) still prints inner object descriptors ([[I@..., [I@...]), so use Arrays.deepToString(grid) when you want nested brackets ("[[1, 2], [3]]").

2. Arrays.sort(arr)

Sorts an array in-place in ascending order and has a void return type:

  • Compile-time trap: System.out.println(Arrays.sort(nums)); fails to compile because println cannot accept void.
  • Primitive order: integral arrays sort numerically. For floating-point arrays, the documented total order places negative zero before positive zero and NaN after all numeric values. There is no sort(boolean[]) overload.
  • String order: lexicographic (UTF-16 code-unit) order, where digits ('0'–'9', codes 48–57) sort before uppercase letters ('A'–'Z', codes 65–90), which sort before lowercase letters ('a'–'z', codes 97–122), and shorter prefixes precede longer ones:
String[] codes = {"a", "10", "A", "2", "Z"};
Arrays.sort(codes);
System.out.println(Arrays.toString(codes)); // [10, 2, A, Z, a]

Notice "10" precedes "2" because '1' (49) is less than '2' (50), and "Z" precedes "a" because 'Z' (90) is less than 'a' (97).

  • Object[] sorting trap: Calling Arrays.sort(new Object[]{"a", 1}) compiles cleanly because the signature accepts Object[], then throws ClassCastException at runtime when String and Integer are compared (or if an element does not implement Comparable).

3. Arrays.binarySearch(arr, key)

Performs binary search on a sorted 1D array:

  • If key is found: returns the non-negative index (>= 0) of a matching element (if duplicates exist, any matching index may be returned).
  • If key is not found: returns -(insertionPoint) - 1, where insertionPoint is the index at which key would be inserted to preserve sorted order. Because insertionPoint >= 0, a not-found result is always strictly negative (< 0).
  • If the array is NOT sorted: the result is undefined under the API contract. Sorting and searching must use the same ordering. An incompatible object comparison can still throw an exception, and an unsorted input does not guarantee any useful index.

Tracing int[] sorted = {10, 20, 30};:

CallFound?Insertion PointReturn Value
Arrays.binarySearch(sorted, 20)Yes (index 1)—1
Arrays.binarySearch(sorted, 5)No0 (before 10)-(0) - 1 = -1
Arrays.binarySearch(sorted, 25)No2 (between 20 and 30)-(2) - 1 = -3
Arrays.binarySearch(sorted, 40)No3 (after 30)-(3) - 1 = -4

Important

Always check whether the array passed to Arrays.binarySearch is actually sorted first. An array can already be sorted. If it is not, sort it with the ordering the search will use before relying on the returned index.

Test Your Knowledge

What is the result of compiling and running the following code?

Object[] items = new String[2];
items[0] = "Java";
items[1] = 8;
System.out.println(items[0]);
A

Fails to compile because String[] cannot be assigned to Object[]

B

Compiles cleanly and throws ArrayStoreException at runtime

C

Fails to compile because 8 is an int, not an Object

D

Compiles cleanly and prints Java

Test Your Knowledge

Assuming import java.util.*;, what does this code print?

String[] vals = {"20", "b", "100", "B"};
Arrays.sort(vals);
System.out.println(Arrays.toString(vals));
A

[20, 100, B, b]

B

[100, 20, b, B]

C

[100, 20, B, b]

D

[B, b, 20, 100]

Test Your Knowledge

Assuming import java.util.*;, what does the following snippet print?

int[] nums = {3, 7, 12, 20};
System.out.println(Arrays.binarySearch(nums, 10));
A

-2

B

2

C

-4

D

-3

Sections you finish are checked off in the contents.