How to check if two arrays are equal or not in Java



Problem Description

How to check if two arrays are equal or not?

Solution

Following example shows how to use equals () method of Arrays to check if two arrays are equal or not.

import java.util.Arrays;

public class Main {
   public static void main(String[] args) throws Exception {
      int[] ary = {1,2,3,4,5,6};
      int[] ary1 = {1,2,3,4,5,6};
      int[] ary2 = {1,2,3,4};
      System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary, ary1));
      System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2));
   }
}

Result

The above code sample will produce the following result.

Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false

Solution

Another sample example of Array compare

import java.util.Arrays;

public class HelloWorld {
   public static void main (String[] args) {
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
      if (Arrays.equals(arr1, arr2)) System.out.println("Same");
      else System.out.println("Not same");
   }
}

Result

The above code sample will produce the following result.

Same   

Solution

Another sample example of Array compare

public class HelloWorld {
   public static void main (String[] args) {
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
      
      if (arr1 == arr2) System.out.println("Same");
      else System.out.println("Not same");
   }
}

Result

The above code sample will produce the following result.

Not same   
java_arrays.htm
Advertisements