How to compare two Arrays in Java to check if they are equal - [String & Integer Array Example]

Hello guys, one of the common Programming, the day-to-date task is to compare two arrays in Java and see if they are equal to each other or not. Of course, you can't compare a String array to an int array, which means two arrays are said to be equal if they are of the same type, has the same length, contains the same elements, and in the same order. Now, you can write your own method for checking array equality or take advantage of Java's rich Collection API. Similar to what you have seen while printing array values in Java, java.util.Arrays class provides convenient methods for comparing array values.

They take care of all four conditions, I have mentioned above. In fact, the Arrays class also provides a deepEquals() method to compare the two-dimensional array in Java. By the way, it's not restricted to just two-dimensional and also valid for any multi-dimensional array.

In this article, we will see examples of comparing two String array, two Integer array, and two multidimensional arrays to learn how to use equals() and deepEquals() methods of java.util.Arrays class.

Btw, if you are not familiar with the array data structure itself then I suggest you first go through a comprehensive course on data a structure like Data Structures and Algorithms: Deep Dive Using Java on Udemy to get an understanding of basic data structures like an array, linked list, binary tree, hash tables, and binary search tree.




1. How to compare two Integer Arrays in Java

In order to compare two integer arrays in Java, all you need to do is import java.util.Arrays class. This class contains two methods related to array comparison equals() and deepEquals(), both are overloaded to accept all primitive arrays and one version for accepting Object array.

We need to use the equals(int[], int[]) method to compare our integer arrays, as shown below. As you can see, I have defined 3 integer arrays, each of the same size but different numbers. int[] even and meEvenToo are equal to each other because they are of the same type, same length, and contains the same number in the same order.

While, int[] odd is not equal to int[] even because though they are of the same type and length, their individual content is different. As expected equals(int[], int[]) method of Arrays class produced correct result.

int[] even = {2, 4, 6};
int[] meEvenToo = {2, 4, 6};
int[] odd = {3, 5, 7};
boolean result = Arrays.equals(even, meEvenToo);
System.out.printf("Comparing two int arrays %s and %s, are they Equal? %s %n ",
                Arrays.toString(even), Arrays.toString(meEvenToo), result);

result = Arrays.equals(even, odd);
System.out.printf("Comparing even and odd int arrays %s and %s, 
                   are they Equal? %s %n",
                Arrays.toString(even), Arrays.toString(odd), result);

Output:
Comparing two int arrays [2, 4, 6] and [2, 4, 6], are they Equal? true
Comparing even and odd int arrays [2, 4, 6] and [3, 5, 7], are they Equal? false

Also, the difference between equals() and deepEquals() is a good Java interview question and asked in a couple of fresher and mid-level interviews.

And,  if you are new to Java and looking for Java-specific things about the array, hash table, and other data structure, there is no better course than The Complete Java Masterclass, which is also the most-up-to course.





2. Comparing two String Array in Java

How to compare Array in Java with Example
As I said in the previous section that java.util.Arrays class has overloaded equals() and deepEquals() to accept object[]. Since arrays are co-variant, you can pass String[] to a method that accepts an Object[], which is used to compare String array in Java.

In this example, we have three string array of length 2, out of three String[] numbers and digits are equal because they also contain the same values at similar index, but String[] numbers and numeric are unequal because their values at respective index are different.

Remember, equality logic of individual object is handled by equals() method of that class itself, which means even string comparison inside the array is case sensitive.

String[] numbers = {"one", "two"};
String[] numeric = {"three", "two"};
String[] digits = {"one", "two"};

result = Arrays.equals(numbers, numeric);
System.out.printf("Comparing two String arrays %s and %s, are they Equal? %s %n ",
                Arrays.toString(numbers), Arrays.toString(numeric), result);

result = Arrays.equals(numbers, digits);
System.out.printf("Comparing two unequal String arrays %s and %s,
                      are they same? %s %n",
                Arrays.toString(numbers), Arrays.toString(digits), result);

Output :
Comparing two String arrays [one, two] and [three, two], are they Equal? false
Comparing two unequal String arrays [one, two] and [one, two], are they same? 
                                      true
If you want to learn more about equals() and deepEquals() method of Array in Java, you can also see The Complete Java Masterclass course on Udemy. One of the most comprehensive courses to learn Java.

best course to learn java in depth





3. How to check two multidimensional arrays are equal in Java

Comparing multi-dimensional arrays is slightly different than comparing one-dimensional arrays because instead of Arrays.equals(), you need to use Arrays.deepEquals().

The tricky part is that the compiler will not catch your array of passing a multi-dimensional array to Arrays.equals() method, which also doesn't throw any exception and simply return false.

This can lead to subtle bugs, sometimes very hard to catch. So, pay special care while comparing the multi-dimensional array and ensure that you have used deepEquals() and not equals().

Here is an example of comparing the two-dimensional array in Java.

char[][] abcd = {{'A', 'B'}, {'C', 'D'}};
char[][] efgh = {{'E', 'F'}, {'G', 'H'}};
char[][] ABCD = {{'A', 'B'}, {'C', 'D'}};

result = Arrays.equals(abcd, efgh);
System.out.printf("Comparing two dimensional arrays %s and %s in Java,
                          Equal? %s %n ",
                Arrays.deepToString(abcd), Arrays.deepToString(efgh), result);

result = Arrays.deepEquals(abcd, ABCD); // using equals() will return false
System.out.printf("Comparing unequal two dimensional char arrays %s and %s 
                  in Java,  are they same? %s %n",
                Arrays.deepToString(abcd), Arrays.deepToString(ABCD), result);

Output:
Comparing two dimensional arrays [[A, B], [C, D]] and [[E, F], [G, H]] in Java,
 Equal? false
Comparing unequal two dimensional char arrays [[A, B], [C, D]] and [[A, B],
 [C, D]] in Java,  are they same? true

If you want to learn more about two-dimensional or multi-dimensional arrays in Java, see Java Fundamentals Part 1 and Part 2 courses on Pluralsight. The first part covers basics like this and the second part covers more advanced concepts of Java Programming.




4. Java Program for Comparing two arrays

Here is the complete code sample of how to compare two arrays in Java. You don't need any third-party library, just JDK. If you are using any IDE like Eclipse or Netbeans, then just copy-paste this code in a Java source file, whose name matches the public class name and run it. Alternatively, you can also run this from the command prompt.

import java.util.Arrays;

/**
 * Java Program to print arrays in Java. We will learn how to print String,
 * int, byte and two dimensional arrays in Java by using toString() and
 * deepToString() method of Arrays class.
 *
 * @author javinpaul
 */
public class ArrayComparisionDemo {

    public static void main(String args[]) {

        // Example 1 : Comparing two int arrays in Java
        int[] even = {2, 4, 6};
        int[] meEvenToo = {2, 4, 6};
        int[] odd = {3, 5, 7};

        boolean result = Arrays.equals(even, meEvenToo);
        System.out.printf("Comparing two int arrays %s and %s, are 
                         they Equal? %s %n ",
                         Arrays.toString(even), Arrays.toString(meEvenToo), 
                                                                result);

        result = Arrays.equals(even, odd);
        System.out.printf("Comparing even and odd int arrays %s and %s,
                             are they Equal? %s %n",
                Arrays.toString(even), Arrays.toString(odd), result);


        // Example 2 : Comparing two String array in Java
        String[] numbers = {"one", "two"};
        String[] numeric = {"three", "two"};
        String[] digits = {"one", "two"};

        result = Arrays.equals(numbers, numeric);
        System.out.printf("Comparing two String arrays %s and %s, 
                                  are they Equal? %s %n ",
                Arrays.toString(numbers), Arrays.toString(numeric), result);

        result = Arrays.equals(numbers, digits);
        System.out.printf("Comparing two unequal String arrays %s and %s, 
                                are they same? %s %n",
                Arrays.toString(numbers), Arrays.toString(digits), result);


        // Example 3 : Comparing two multi-dimensional array in Java
        char[][] abcd = {{'A', 'B'}, {'C', 'D'}};
        char[][] efgh = {{'E', 'F'}, {'G', 'H'}};
        char[][] ABCD = {{'A', 'B'}, {'C', 'D'}};

        result = Arrays.equals(abcd, efgh);
        System.out.printf("Comparing two dimensional arrays %s and %s in Java,
                                Equal? %s %n",
                Arrays.deepToString(abcd), Arrays.deepToString(efgh), result);

        result = Arrays.deepEquals(abcd, ABCD); // using equals() will return false
        System.out.printf("Comparing unequal two dimensional char arrays %s 
                               and %s in Java, are they same? %s %n",
                Arrays.deepToString(abcd), Arrays.deepToString(ABCD), result);
    }
}

Output:
Comparing two int arrays [2, 4, 6] and [2, 4, 6], are they Equal? true
Comparing even and odd int arrays [2, 4, 6] and [3, 5, 7], are they Equal? false
Comparing two String arrays [one, two] and [three, two], are they Equal? false
Comparing two unequal String arrays [one, two] and [one, two], are they same? true
Comparing two dimensional arrays [[A, B], [C, D]] and [[E, F], [G, H]] in Java,
           Equal?  false
Comparing unequal two dimensional char arrays [[A, B], [C, D]] 
                   and [[A, B], [C, D]] in Java, are they same? true

That's all about how to compare two arrays in Java. By using equals() and deepEquals() method of java.util.Arrays class, you can easily compare any arbitrary array in Java. We have seen examples of comparing String arrays, int arrays, and multi-dimensional arrays in Java programs.

One thing to note is that you must use the deepEquals() method to compare two-dimensional arrays in Java, using equals() in such case does not produce the correct result. Do you know any other clever way to compare array in Java?


Other Array related coding Interview Questions for practice:
  • How to find all pairs in an array whose sum is equal to k (solution)
  • How to rotate a given array in Java? (solution)
  • 10 Algorithms Books Every Programmer should read [books]
  • How to find one missing number in a sorted array? (solution)
  • How to check if an array contains a particular value? (solution)
  • How to find duplicates from an unsorted array in Java? (solution)
  • How to remove duplicates from an array in Java? (solution)
  • How to find the missing number from a given array in Java? (solution)
  • 30+ Array-based Coding Problems from Interviews (questions)
  • 10 Free Data Structure and Algorithms Courses for Programmers [courses]
  • Write a program to find the missing number in an integer array of 1 to 100? [solution]
  • How to find the largest and smallest number in an array without sorting? (solution)
  • 50+ Data Structure and Algorithms Coding Problems from Interviews (questions)
  • How do you reverse an array in place in Java? [solution]
  • 10 Algorithms courses to Crack Coding Interviews [courses]

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data Structure and Algorithms courses on Udemy.

4 comments:

  1. good explanation

    ReplyDelete
  2. Thanks for the clear explanation!

    ReplyDelete
  3. hi i want a java program for,taking input like 0101000111001000110000 and print the output if u find 000 in our input print 0 and same find 100 print 1

    eg; in given input 0101000111001000110000 the o/p----10110

    ReplyDelete
  4. Thank You. Really helpful.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.