Test Equality Of Two Arrays | Java Programs

Output:

Running Program:-

*** Checking Equality Of Two Arrays ***

First Array is: 21 35 67 29 11 
Second Array is: 21 5 67 29 11 

Two  arrays are not equal.
-----------------------------------------
Running Program:-

*** Checking Equality Of Two Arrays ***

First Array is: 1 3 6 2 1 
Second Array is: 1 3 6 2 1 

Two arrays are equal.

Click Here For Java Online Compiler

Solution:

class TwoArraysEqualOrNot {

    static void check(int[] array1, int[] array2) {
        boolean equalOrNot = true;

        if (array1.length == array2.length) {
            for (int i = 0; i < array1.length; i++) {
                if (array1[i] != array2[i]) {
                    equalOrNot = false;
                }
            }
        } else {
            equalOrNot = false;
        }

        if (equalOrNot) {
            System.out.println("Two arrays are equal.");
        } else {
            System.out.println("Two  arrays are not equal.");
        }
    }

    public static void main(String[] args) {
        int[] array1 = {21, 35, 67, 29, 11};
        int[] array2 = {21, 5, 67, 29, 11};
        System.out.println("*** Checking Equality Of Two Arrays ***" + "\n");
        System.out.print("First Array is: ");
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + " ");
        }
        System.out.println();
        System.out.print("Second Array is: ");
        for (int i = 0; i < array2.length; i++) {
            System.out.print(array2[i] + " ");
        }
        System.out.println("\n");
        check(array1, array2);
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon