Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
Comparing Java arrays with Arrays.equals, Arrays.compare and Arrays.mismatch and their ordering rules, varargs parameters used as arrays, and arrays of arrays: declarations, rectangular and jagged creation, nested loops, deepToString and deepEquals.
kvi5hnuCode Sprout team member7 min readOn this page
Article 20 showed that == and equals on arrays compare references. The java.util.Arrays class adds three methods that compare contents: equals, compare and mismatch. The exam asks for their exact return values. This article also covers varargs, which are arrays in disguise, and Java's take on multidimensional arrays, which are really arrays of arrays and can be jagged.
Arrays.equals
static boolean equals(int[] a, int[] b) // overloads for every primitive type and Object[]
Two arrays are equal if they have the same length and equal elements in the same order. Primitives are compared with == and objects with equals. Two null arrays are equal.
new int[] {1} == new int[] {1}; // false: two objects
Arrays.equals(new int[] {1}, new int[] {1}); // true
Arrays.equals(new int[] {1}, new int[] {1, 2}); // false: different lengths
Arrays.equals(new String[] {"a"}, new String[] {new String("a")}); // true: uses String.equals
Arrays.compare
compare puts two arrays in lexicographic order, the way a dictionary orders words. It returns an int, and only its sign matters:
- negative: the first array is smaller;
- zero: the arrays are equal;
- positive: the first array is larger.
The algorithm:
- Walk both arrays from index 0. At the first index where the elements differ, the result is the comparison of those two elements.
- If one array runs out first and every element up to that point was equal, the shorter array is smaller.
- Same length and all elements equal: zero.
Elements are compared by their natural order:
- numbers by value;
- strings with
compareTo: by character value, so digits < uppercase < lowercase, and a prefix is smaller than the longer string; nullelements are smaller than any non-null element, and anullarray is smaller than any array.
| First | Second | Sign | Reason |
|---|---|---|---|
{1, 2} | {1} | positive | Same so far, and the first is longer |
{1, 2} | {1, 2} | zero | Identical |
{1, 2} | {5} | negative | First difference: 1 < 5 (length doesn't matter) |
{"a"} | {"aa"} | negative | "a" is a prefix of "aa" |
{"a"} | {"A"} | positive | 'a' (97) > 'A' (65) |
{"a"} | {null} | positive | null is smallest |
The first difference decides: compare({5}, {1, 9}) is positive even though the second array is longer. Both arrays must have the same type. Arrays.compare(new int[] {1}, new String[] {"a"}) doesn't compile, because no overload takes those two types.
Arrays.mismatch
mismatch returns the index of the first difference, or -1 if the arrays are equal. If one array is a prefix of the other, the result is the length of the shorter one, since that's the first index where only one array has an element:
Arrays.mismatch(new int[] {1}, new int[] {1}); // -1
Arrays.mismatch(new String[] {"a"}, new String[] {"A"}); // 0
Arrays.mismatch(new int[] {1, 2}, new int[] {1}); // 1
Arrays.mismatch(new int[] {4, 5, 6}, new int[] {4, 5, 7}); // 2
| Method | Arrays with the same contents | Different arrays |
|---|---|---|
Arrays.equals | true | false |
Arrays.compare | 0 | Negative or positive |
Arrays.mismatch | -1 | 0 or a positive index |
All three have range overloads (Java 9) that compare slices: Arrays.equals(a, aFrom, aTo, b, bFrom, bTo). As always, the end index is exclusive.
Varargs
A varargs parameter (Type... name) lets a caller pass any number of arguments, including none. Inside the method, it is an array:
static double average(String label, int... values) {
if (values.length == 0) return 0; // values is an int[]
int total = 0;
for (int v : values) total += v;
return (double) total / values.length;
}
average("none"); // values = new int[0] (never null here)
average("three", 4, 8, 6); // values = {4, 8, 6}
average("array", new int[] {10, 20}); // an existing array is passed straight in
Rules you need for now (Chapter 5 covers calling and overloading in depth):
- A method can have only one varargs parameter, and it must be last:
m(int... a, String b)doesn't compile. String... argsandString[] argshave the same signature, so a class can't declare both overloads. That's also whymain(String... args)is a valid entry point.- Calling with no arguments passes an empty array, not
null. Passingnullexplicitly gives anullarray.
Arrays of arrays
Java doesn't have true multidimensional arrays. It has arrays whose elements are references to other arrays. Brackets can go on the type, on the name or both, and they add up:
int[][] grid1; // 2D
int grid2[][]; // 2D
int[] grid3[]; // 2D (legal, but please don't)
int[] flat, deep[]; // flat is int[], deep is int[][]
int[] vars4[], space[][]; // vars4 is 2D, space is 3D
Creating them
String[][] seats = new String[3][2]; // 3 rows, each a String[2] full of nulls
seats[0][1] = "Ada"; // [[null, Ada], [null, null], [null, null]]
int[][] jagged = {{2, 6}, {5}, {8, 1, 3}}; // rows may have different lengths
int[][] lazy = new int[2][]; // only the outer array exists
lazy[0] = new int[3];
lazy[1] = new int[] {42};
int[][][] cube = new int[2][3][4]; // 2 × 3 × 4
![jagged refers to an outer array of three slots; each slot refers to its own int array of length 2 (2, 6), 1 (5) and 3 (8, 1, 3); jagged[2][0] is 8. new int[2][] creates only the outer array, whose slots are null until rows are assigned](https://code-sprout-content.laxmi.solutions/asset/2026/11/az4y6byyiugbcbyp.png)
- The first size is required. Later sizes can be left out, but only from the right:
new int[2][]is legal,new int[][2]isn't. - With
new int[2][], the rows arenull.lazy[0][0] = 1;before a row is assigned throwsNullPointerException. int[] a = new int[2][3];doesn't compile (it's anint[][]), and neither doesint[][] b = {1, 2};(the elements must be arrays).
Using them
grid[i] is a whole row, an int[], and grid[i][j] is one element. Each row has its own length, so loops should use grid[i].length, not a fixed width:
for (int i = 0; i < jagged.length; i++) {
for (int j = 0; j < jagged[i].length; j++) {
System.out.print(jagged[i][j] + " ");
}
System.out.println();
}
for (int[] row : jagged) { // the same with for-each
for (int value : row) System.out.print(value + " ");
System.out.println();
}
The one-level methods from Arrays don't look inside the rows. Arrays.toString(jagged) prints [[I@…, [I@…, …], and Arrays.equals(jagged, copy) compares the row references. Use Arrays.deepToString and Arrays.deepEquals for nested arrays.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
Arrays.equals,compareandmismatchwith ranges date from Java 9. Varargs and multidimensional arrays haven't changed since Java 5.
Exam traps from this article
A complete example
import java.util.Arrays;
public class Solution {
// A varargs parameter is an array inside the method
static double average(String label, int... values) {
if (values.length == 0) {
System.out.println(label + ": no values");
return 0;
}
int total = 0;
for (int v : values) {
total += v;
}
double avg = (double) total / values.length;
System.out.println(label + ": " + values.length + " values, first " + values[0] + ", average " + avg);
return avg;
}
static String sign(int n) {
return n < 0 ? "negative" : n == 0 ? "zero" : "positive";
}
public static void main(String[] args) {
System.out.println("-- equals / compare / mismatch --");
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = {1, 2};
int[] d = {5};
System.out.println("a == b: " + (a == b) + ", a.equals(b): " + a.equals(b)
+ ", Arrays.equals(a, b): " + Arrays.equals(a, b));
System.out.println("compare(a, b) " + sign(Arrays.compare(a, b))
+ ", compare(a, c) " + sign(Arrays.compare(a, c))
+ ", compare(c, d) " + sign(Arrays.compare(c, d)));
String[] lower = {"a"};
String[] upper = {"A"};
String[] withNull = {null};
System.out.println("{\"a\"} vs {\"A\"}: " + sign(Arrays.compare(lower, upper))
+ ", {\"a\"} vs {null}: " + sign(Arrays.compare(lower, withNull)));
System.out.println("mismatch(a, b) " + Arrays.mismatch(a, b)
+ ", mismatch(a, c) " + Arrays.mismatch(a, c)
+ ", mismatch(a, {1, 9, 3}) " + Arrays.mismatch(a, new int[] {1, 9, 3}));
System.out.println("-- varargs --");
average("none");
average("three", 4, 8, 6);
average("array", new int[] {10, 20});
System.out.println("-- arrays of arrays --");
String[][] seats = new String[3][2];
seats[0][1] = "Ada";
System.out.println(Arrays.deepToString(seats));
int[][] jagged = {{2, 6}, {5}, {8, 1, 3}};
System.out.println("rows " + jagged.length + ", row lengths "
+ jagged[0].length + " " + jagged[1].length + " " + jagged[2].length);
for (int[] row : jagged) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
int[][] lazy = new int[2][]; // second dimension left out
System.out.println(Arrays.toString(lazy));
lazy[0] = new int[3];
lazy[1] = new int[] {42};
System.out.println(Arrays.deepToString(lazy));
int[][] copy = {{2, 6}, {5}, {8, 1, 3}};
System.out.println("equals " + Arrays.equals(jagged, copy)
+ ", deepEquals " + Arrays.deepEquals(jagged, copy));
int[][][] cube = new int[2][3][4];
System.out.println("cube " + cube.length + "x" + cube[0].length + "x" + cube[0][0].length);
}
}
Output:
-- equals / compare / mismatch --
a == b: false, a.equals(b): false, Arrays.equals(a, b): true
compare(a, b) zero, compare(a, c) positive, compare(c, d) negative
{"a"} vs {"A"}: positive, {"a"} vs {null}: positive
mismatch(a, b) -1, mismatch(a, c) 2, mismatch(a, {1, 9, 3}) 1
-- varargs --
none: no values
three: 3 values, first 4, average 6.0
array: 2 values, first 10, average 15.0
-- arrays of arrays --
[[null, Ada], [null, null], [null, null]]
rows 3, row lengths 2 1 3
2 6
5
8 1 3
[null, null]
[[0, 0, 0], [42]]
equals false, deepEquals true
cube 2x3x4
Points to notice:
compare(c, d)is negative because the first elements differ (1 < 5), even thoughcis longer.mismatch(a, c)is 2, the length of the shorter array, becausecis a prefix ofa.average("none")receives an empty array, notnull, and the version with an explicit array receives that array.new int[2][]prints[null, null]until the rows are assigned.Arrays.equalson two equal-looking jagged arrays isfalse.deepEqualsistrue.
Common questions
What does Arrays.compare return exactly?
For primitives it's usually -1, 0 or 1, and for objects it's the element's compareTo result (32 for "a" versus "A"). The exam asks only for the sign, as Comparator does.
Is int[][] stored as one block of memory?
No. It's an array of references to separate int[] objects, which is why rows can have different lengths and why each row can be replaced independently.
Can varargs be null?
Only if a caller passes null explicitly or as an array variable. Calling with no arguments gives an empty array, so checking values.length is enough for normal calls.
What's the difference between deepEquals and equals for 1D arrays?
deepEquals takes only Object[] arguments, so it doesn't even compile with two int[] arrays; use Arrays.equals for those. For 1D arrays of objects, the two give the same result. deepEquals only differs when elements are themselves arrays, which it compares recursively.
Summary
Arrays.equals: same length and equal elements in order.Arrays.compare: the first differing element decides. A prefix is smaller,nullis smallest, and both arrays must be the same type. Only the sign matters.Arrays.mismatch: -1 if equal, otherwise the first differing index (the shorter length for a prefix).- Varargs (
T... x) is a single, last parameter that behaves as an array inside the method. - Multidimensional arrays are arrays of arrays: brackets add up, rows can be jagged or
null, anddeepToString/deepEqualslook inside them.
Practice quiz
Test yourself with the array comparison and multidimensional arrays quiz: 10 exam-style questions with explanations.
Previous: Java Arrays: Creating, Sorting and Searching (OCP 21)
Related reading
- Java Arrays: Creating, Sorting and Searching (OCP 21)
- Java String Equality: ==, equals, the String Pool and intern (OCP 21)
- Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
- Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
- Java Strings: Creation, Concatenation and Immutability (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.