1.

Compare two Java arrays

Answer»

Two arrays in Java are SAID to be equal if they have the same number of elements and all the corresponding elements are also the same. So, the two arrays can be compared in Java by using the Arrays.equals() method.

A program that demonstrates this method is given as follows:

import java.util.Arrays; PUBLIC class DEMO {    public static void MAIN (STRING[] args)      {        int arr1[] = {5, 2, 9, 7, 1};        int arr2[] = {5, 2, 9, 7, 1};        int i;        System.out.print("Array 1: ");        for (i=0; i<5; i++)          System.out.print(arr1[i] + " ");        System.out.print("\nArray 2: ");        for (i=0; i<5; i++)          System.out.print(arr2[i] + " ");        if (Arrays.equals(arr1, arr2))            System.out.println("\nThe above two arrays are the same");        else            System.out.println("\nThe above two arrays are not the same");    } }

The output of the above program is as follows:

Array 1: 5 2 9 7 1 Array 2: 5 2 9 7 1 The above two arrays are the same


Discussion

No Comment Found