How to test array equality in Java

Two arrays are equal if all their values are equal and in the same order.

svg viewer

Arrays.equals()

The Arrays.equals method can be used to check if two arrays are equal.

This method takes two arrays as arguments.

import java.util.Arrays;
class ArrayEquality {
public static void main( String args[] ) {
int [] arr1 = new int [] {20, 5, -95, 43, 17};
int [] arr2 = new int [] {20, 5, -95, 43, 17};
System.out.println(Arrays.equals(arr1, arr2));
}
}

Note that a shallow comparison is performed, i.e., it checks:

arr1[0].equals(arr2[0]),
arr1[1].equals(arr2[1]),
...

This is not suitable for multidimensional arrays.

Arrays.deepEquals()

The Arrays.deepEquals() method is a more effective way of testing the equality of multidimensional arrays.

This method takes two arrays as arguments.

import java.util.Arrays;
class ArrayEquality {
public static void main( String args[] ) {
int [][] arr1 = {{20, 5},
{-95, 43},
{17, 22}};
int [][] arr2 = {{20, 5},
{-95, 43},
{17, 22}};
System.out.println(Arrays.deepEquals(arr1, arr2));
}
}

This method recurses on the arrays and compares the actual elements. It can be used with single-dimension arrays as well.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources

Attributions:
  1. undefined by undefined
Copyright ©2025 Educative, Inc. All rights reserved