How to Compare Two Arrays in Java

Let’s see, How can you compare Two Arrays in Java to verify,  If they are equal to each other or not.

Please note you can’t compare a String array to an int array. You can compare the Array only if they have the same data type.

 

Compare Two Arrays in Java

To compare two integer array in Java, you need to import java.util.Arrays class. This class contains two methods related to array comparison equals() and deepEquals(). Let’s see, How can we compare the Integer Array in Java-

Output :

Comparing two int arrays [1, 7, 9, 12] and [1, 7, 9, 12], are they Equal? true

Comparing even and odd int arrays [1, 7, 9, 12] and [9, 12, 8, 1], are they Equal? false

Compare Two String Arrays in Java

You can compare the String Array using the same way we have compared the Integer Array in our last example.

Output :

Comparing two String arrays [BMW, Audi, Volvo] and [Hundai, Tata, Ford], are they Equal? false

Comparing two unequal String arrays [BMW, Audi, Volvo] and [BMW, Audi, Volvo], are they same? true

 

Compare Two Arrays in Java without in-built Method

Let’s see how can you compare the Array in Java without inbuilt method or programmatically. Let’s implement the logic.

In below example, we will  see how to compare the Array without Arrays class equals() method. For similarity first size of the array should be same. So first we will compare the size of both arrays if the size of both arrays is same then we will compare the Elements of the first array with the element of the second array one by one. Let’s see the implementation-

Output :

Comparing two int arrays [1, 7, 9, 12] and [1, 7, 9, 12], are they Equal? true

Comparing two int arrays [1, 7, 9, 12] and [9, 12, 8, 1], are they Equal? false

That’s all about how to compare two arrays in Java By using equals() method of java.util.Arrays class or without java inbuilt method i.e How can you compare the Array Programmatically.

0 Comment

Leave a Reply