Compare Two Arrays in Java
Problem
Two arrays are considered equal when they have the same length and every element matches at the same position.
Given two arrays of integers, determine whether they are equal.
Java Program
public class CompareTwoArrays {
public static void main(String[] args) {
int[] arr1 = {4, 8, 15, 16};
int[] arr2 = {4, 8, 15, 16};
boolean equal = arr1.length == arr2.length;
if (equal) {
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
equal = false;
break; // mismatch found, no need to keep checking
}
}
}
System.out.println("Arrays are equal: " + equal);
}
}Output
Core Logic
Checking the lengths first, then comparing every position one by one, confirms whether the two arrays truly match.
- 1
arr1.length == arr2.lengthis checked first — arrays of different lengths can never be equal. - 2If the lengths match, a loop compares
arr1[i]againstarr2[i]at every index. - 3The first mismatch found sets
equaltofalseand exits the loop immediately withbreak. - 4If every position matches,
equalstaystruefor the whole scan.
[4, 8, 15, 16] and [4, 8, 15, 16], every position matches, so equal stays true.Key Point: arr1 == arr2 would compare object references, not contents — two separate arrays holding identical values would still report false with ==, which is why this checks each element individually instead.
Why: Each position is checked once, and the loop exits at the first mismatch found, without allocating anything beyond a boolean flag.
Key Concepts
Approach 2: Using Arrays.equals()
import java.util.Arrays;
public class CompareTwoArraysBuiltin {
public static void main(String[] args) {
int[] arr1 = {4, 8, 15, 16};
int[] arr2 = {4, 8, 15, 16};
// Arrays.equals() checks both length and every element in one call
boolean equal = Arrays.equals(arr1, arr2);
System.out.println("Arrays are equal: " + equal);
}
}
Output
Core Logic
In real code, there's no reason to write the comparison loop yourself — Arrays.equals() already checks both length and contents in one call.
- 1
Arrays.equals(arr1, arr2)takes both arrays and returns a single boolean. - 2Internally, it performs the same length check and element-by-element comparison as the manual loop.
- 3No explicit loop is needed in your own code.
Arrays.equals(new int[]{4, 8, 15, 16}, new int[]{4, 8, 15, 16}) returns true in a single call.Key Point: This is the version to actually use — the manual loop exists only to show what Arrays.equals() is conceptually doing under the hood.
Why: Arrays.equals() still performs the same kind of element-by-element scan internally, but that scan happens inside the JDK instead of your own loop.