Java program to check if given 2 arrays are equal or not

Problem Statment: 

How to check if the given 2 arrays are equal or not ?

Solution Approach:

  • Check the 2 arrays using equals() method
  • Check the 2 Arrays using == comparison 
package com.java.planforexams.array;
import java.util.Arrays;
public class IfArraysAreEqual {
	public static void main(String[] args) {
		  int[] arraySet1 = {11,21,31,41,51};
	      int[] arraySet2 = {11,21,31,41,51};
	      int[] arraySet3 = {51,41,31,21,11};;
	      System.out.println(" Checking Arrays Equality using equals() method");
	      System.out.println("Is array 1 equal to array 2?? " + 
                             Arrays.equals(arraySet1, arraySet2));
	      System.out.println("Is array 1 equal to array 3?? " + 
                             Arrays.equals(arraySet2, arraySet3));
	      
	      System.out.println(" Checking Arrays Equality using == comparison");
	      if (arraySet1 == arraySet2) System.out.println("Array Set 1 and Array
                                                         Set 2 are equal");
	      else System.out.println("Array Set 1 and Array Set 2 are NOT  equal");
	      if (arraySet1 == arraySet3) System.out.println("Array Set 1 and Array 
                                                         Set 3 are equal");
	      else System.out.println("Array Set 1 and Array Set 3 are NOT  equal");
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*