Title: Check if Two Arrays are Equal
Comparing two arrays for equality looks trivial at first glance, but Java’s default == operator, and even the inherited equals() method, do not compare array contents the way beginners expect. In this guide, you’ll learn exactly what “equal arrays” means in Java, and you’ll build a method that checks it correctly.
We’ll walk through the algorithm step by step, trace it on a sample input, and cover the common mistakes, edge cases, and interview follow-up questions that come up when this problem shows up in a coding interview.
Understanding the Problem
Two arrays are considered equal when they have the same length and every element at the same index matches in both arrays. For example, {1, 2, 3} and {1, 2, 3} are equal, but {1, 2, 3} and {3, 2, 1} are not, even though they contain the same values.
A common beginner mistake is to use arr1 == arr2 or arr1.equals(arr2) to check this. Both compare object references, not contents, because arrays in Java do not override equals(). Two arrays with identical elements will still be reported as unequal unless they are literally the same object in memory.
Approach
- Check if either array reference is
null. If both arenull, treat them as equal; if only one isnull, they are not equal. - Compare the
lengthof both arrays. If the lengths differ, the arrays cannot be equal. - Loop through the arrays with a single index
ifrom0tolength - 1. - At each index, compare
arr1[i]witharr2[i]. If they differ, returnfalseimmediately. - If the loop completes without finding a mismatch, return
true.
Java Program
public class CheckIfTwoArraysAreEqual {
public static boolean areArraysEqual(int[] arr1, int[] arr2) {
if (arr1 == null || arr2 == null) {
return arr1 == arr2;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 3, 4, 5};
int[] arr3 = {1, 2, 3, 4, 6};
System.out.println("arr1 vs arr2: " + areArraysEqual(arr1, arr2));
System.out.println("arr1 vs arr3: " + areArraysEqual(arr1, arr3));
}
}Explanation of the Program
- The method
areArraysEqualfirst guards againstnullreferences so the rest of the logic never throws aNullPointerException. - The length check short-circuits the comparison. Arrays of different sizes can never be equal, so there is no reason to enter the loop.
- The
forloop walks both arrays in lock step using one index. As soon asarr1[i] != arr2[i], the method returnsfalseand skips the remaining elements. - If the loop finishes without returning, every index matched, so the method returns
true. - The
mainmethod demonstrates the behavior on one equal pair and one pair that differs in the last element.
Step-by-Step Trace
Let’s trace areArraysEqual on arr1 = {3, 6, 9, 12, 15} and arr2 = {3, 6, 9, 11, 15}, which should produce false because the values at index 3 differ.
| Iteration | arr1[i] | arr2[i] | arr1[i] == arr2[i]? | Action |
|---|---|---|---|---|
| 0 | 3 | 3 | yes | continue loop |
| 1 | 6 | 6 | yes | continue loop |
| 2 | 9 | 9 | yes | continue loop |
| 3 | 12 | 11 | no | return false |
At the end of each iteration where arr1[i] equals arr2[i], the loop simply advances to the next index; the moment a mismatch is found, the method returns false right away and the remaining indices are never checked.
Examples
Example 1: Equal Arrays
Two arrays with identical elements in the same order return true.
int[] arr1 = {10, 20, 30};
int[] arr2 = {10, 20, 30};
System.out.println(areArraysEqual(arr1, arr2));
// Output: trueExample 2: Arrays of Different Lengths
When the lengths differ, the method returns false immediately, without comparing a single element.
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3, 4};
System.out.println(areArraysEqual(arr1, arr2));
// Output: falseExample 3: Same Elements in a Different Order
Arrays containing the same values in a different order are not equal under this definition, because order matters at every index.
int[] arr1 = {1, 2, 3};
int[] arr2 = {3, 2, 1};
System.out.println(areArraysEqual(arr1, arr2));
// Output: falseCommon Mistakes to Avoid
These are the mistakes that trip up most learners the first time they solve this problem.
- Comparing arrays with == –
arr1 == arr2checks whether both variables point to the same object, so two arrays with identical content but different memory addresses are wrongly reported as unequal. Compare elements instead. - Calling arr1.equals(arr2) – arrays never override
equals(), so this behaves exactly like==and still compares references. Use a manual loop orArrays.equals(). - Skipping the length check – looping up to
arr1.lengthwhenarr2is shorter throws anArrayIndexOutOfBoundsException. Always compare lengths before the loop. - Forgetting the null check – calling
arr1.lengthon anullreference throws aNullPointerExceptionbefore the comparison even starts. Guard againstnullfirst.
Edge Cases to Test
Before calling the problem solved, make sure the method handles these inputs correctly.
- Two empty arrays
- Arrays of different lengths
- Single-element arrays
- One or both array references null
- Arrays with duplicate elements
- Same elements in a different order
- Arrays containing negative numbers or zero
Additional Considerations
The loop-based comparison runs in O(n) time, where n is the length of the shorter array, since the method returns as soon as it finds a mismatch. It uses O(1) extra space because it only tracks a single loop index.
Java’s standard library already provides this behavior through Arrays.equals(arr1, arr2) for one-dimensional arrays and Arrays.deepEquals(arr1, arr2) for nested arrays. Writing the method by hand, as shown above, is valuable for interviews because it proves you understand why the built-in methods exist in the first place.
Interview Follow-up Questions
Once you can solve the base problem, expect an interviewer to push further with questions like these.
- What if order should not matter? – sort copies of both arrays first and then compare them element by element, or count element frequencies with a
HashMapto avoid mutating the originals. - What if the arrays are two-dimensional? – use
Arrays.deepEquals(), or recursively apply the same length-and-element comparison to each row. - What if the arrays hold objects instead of primitives? – the comparison now depends on how each object’s
equals()method is implemented, so an incorrect override can silently break the result. - What if the arrays are too large to hold in memory at once? – stream both arrays from disk in matching chunks and compare chunk by chunk, failing fast on the first mismatched chunk instead of loading everything upfront.
Conclusion
Checking array equality in Java comes down to comparing lengths first and then walking both arrays together, element by element, since the default == and equals() behavior only compares references. Once you internalize that distinction, the rest of the method is a straightforward loop.
Try adapting this method to compare arrays of String or custom objects, and notice how the correctness of the result depends on how equality is defined for those types. You can find more array-based problems and solutions like this one in the Arrays section of the blog.



