How to Compare Arrays in Java with Examples

CodeForHunger
2 min readSep 3, 2024

--

In this post, we will learn how to compare two arrays in Java. But, before that we need to understand what comparing arrays really means. So without wasting more time let's get started.

How to Compare Arrays in Java with Examples, How to compare two arrays in Java

What does comparing arrays really mean?

Comparing arrays means comparing or we can say checking first array elements are the same as another one or not. For Example: If we have two arrays like we can say arr1[] or arr2[] here, arr1 contains some values like 1,2,3,4,5, or arr2[] contains some values like 6,7,8,9,10. So we can see that arr1[] and arr2[] contains different values.

Let’s understand it with programming examples :)

Java provides two inbuilt methods to compare arrays:

  1. Arrays.equals()
  2. Arrays.deepEquals()

1. Java Program to Compare two arrays using equals() method:

import java.util.Arrays;

public class ComparingArrays {

public static void main(String[] args) {
int arr1[] = {1,2,3,4,5};
int arr2[] = {6,7,8,9,10};

//comparing array contents
if(Arrays.equals(arr1,arr2))
System.out.println("Given two arrays are the same");
else
System.out.println("Given arrays are not the same");

}
}

The output of the above program is:

Given arrays are not the same

2. Java Program to Compare two arrays using deepEquals() method:

This method deeply compares two arrays. It is most useful when we want to compare multidimensional arrays.

import java.util.Arrays;

public class ComparingArrays {

public static void main(String[] args) {
int arr1[] = {1,2,3,4,5};
int arr2[] = {1,2,3,4,5};

//a1[] and a2[] contains only one elements
Object a1[] = {arr1};
Object a2[] = {arr2};

//deeply comparing array contents
if(Arrays.deepEquals(a1,a2))
System.out.println("Given two arrays are the same");
else
System.out.println("Given arrays are not the same");

}

}

The output of the above program is:

Given two arrays are the same

Same above program using a multidimensional array:

import java.util.Arrays;

public class ComparingArrays {

public static void main(String[] args) {
//defining multidimensional arrays
int arr1[][] = {{1,2},{3,4}};
int arr2[][] = {{1,2},{3,4}};

//a1[] and a2[] contains only one elements
Object a1[] = {arr1};
Object a2[] = {arr2};

//deeply comparing multidimensional array contents
if(Arrays.deepEquals(a1,a2))
System.out.println("Given two arrays are the same");
else
System.out.println("Given arrays are not the same");

}
}

The output of the above program is:

Given two arrays are the same

Thanks for reading this article so far if you have any questions or doubts then you can share them in the comment section given below……. :)

Originally published at https://codeforhunger.blogspot.com.

--

--

CodeForHunger

Here, I will share tips & tricks to learn programming languages, Learn C and Java with lot of exercises, coding examples & interview questions. Follow for more.