6.3 Array Reference Behavior & java.util.Arrays Helpers
Key Takeaways
An array is an object. Its inherited
equalstests reference identity, and its inheritedtoStringincludes the type name and a hash code.Primitive arrays are invariant (
int[]cannot be assigned tolong[]ordouble[]), whereas reference-type arrays are covariant (String[]assigns toObject[]).Writing a mismatched object type such as
Integerinto anObject[]reference backed by aString[]compiles cleanly and throwsArrayStoreExceptionat runtime.Arrays.sortsorts in place. Use natural ordering forString, where comparison uses UTF-16 code units. Incomparable object elements can causeClassCastException.On a correctly sorted array,
Arrays.binarySearchreturns a matching index or-insertionPoint - 1. The API leaves the result undefined if the array is unsorted.
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[].
| Assignment | Compiles? | Why |
|---|---|---|
Object o = new int[]{1, 2}; | Yes | Every array (even primitive) is an Object |
Object[] oa = new int[]{1, 2}; | No | int is not a reference type, so int[] is not an Object[] |
long[] ls = new int[]{1, 2}; | No | Primitive arrays are invariant (int[] is not a long[]) |
Object[] objs = new String[]{"a"}; | Yes | Reference arrays are covariant (String extends Object) |
CharSequence[] cs = new String[]{"a"}; | Yes | String 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 becauseprintlncannot acceptvoid. - 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. Stringorder: lexicographic (UTF-16 code-unit) order, where digits ('0'–'9', codes48–57) sort before uppercase letters ('A'–'Z', codes65–90), which sort before lowercase letters ('a'–'z', codes97–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: CallingArrays.sort(new Object[]{"a", 1})compiles cleanly because the signature acceptsObject[], then throwsClassCastExceptionat runtime whenStringandIntegerare compared (or if an element does not implementComparable).
3. Arrays.binarySearch(arr, key)
Performs binary search on a sorted 1D array:
- If
keyis found: returns the non-negative index (>= 0) of a matching element (if duplicates exist, any matching index may be returned). - If
keyis not found: returns-(insertionPoint) - 1, whereinsertionPointis the index at whichkeywould be inserted to preserve sorted order. BecauseinsertionPoint >= 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};:
| Call | Found? | Insertion Point | Return Value |
|---|---|---|---|
Arrays.binarySearch(sorted, 20) | Yes (index 1) | — | 1 |
Arrays.binarySearch(sorted, 5) | No | 0 (before 10) | -(0) - 1 = -1 |
Arrays.binarySearch(sorted, 25) | No | 2 (between 20 and 30) | -(2) - 1 = -3 |
Arrays.binarySearch(sorted, 40) | No | 3 (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.
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]);
Fails to compile because String[] cannot be assigned to Object[]
Compiles cleanly and throws ArrayStoreException at runtime
Fails to compile because 8 is an int, not an Object
Compiles cleanly and prints Java
Assuming import java.util.*;, what does this code print?
String[] vals = {"20", "b", "100", "B"};
Arrays.sort(vals);
System.out.println(Arrays.toString(vals));
[20, 100, B, b]
[100, 20, b, B]
[100, 20, B, b]
[B, b, 20, 100]
Assuming import java.util.*;, what does the following snippet print?
int[] nums = {3, 7, 12, 20};
System.out.println(Arrays.binarySearch(nums, 10));
-2
2
-4
-3
Sections you finish are checked off in the contents.