Check if two arrays are equal or not in Java

In this tutorial, we will learn how to check if two arrays are equal or not in Java. Firstly, using a simple program and secondly using a predefined library to do the same.
We will describe how two arrays can be equal when it fulfills two conditions.
1. No. of elements in the arrays is equal.
2. Values in the array should be the same even though they are not arranged properly.

for example:

check if two arrays are equal or not in Java

 Two arrays are equal or not in java

Basic Approach in this program:
1. Firstly, check no of an element in the first array should be equal to the two-second one.
2. If the number of elements is equal but their arrangement is not in the proper way then using sort we sort both arrays.

Program without predefined library

 package array;
import java.util.Arrays;
public class Array {
public static boolean isequal(int a[],int b[],int len1,int len2)
{  //to sort both the arrays
   for(int i=0;i<len1;i++)
   { if(a[i]!=b[i])
   return false; 
  return true;
    return true;
public static void main(String[] args) {
       int a[]={1,4,6,8,36};
       int b[]={1,4,36,6};
       //to find length of both arrays
       int len1=a.length;
       int len2=b.length;
       {System.out.println("not equal");
       {System.out.println(" equal");}
           {System.out.println(" not equal");}
not equal

Program with a predefined library

package comparearray;
import java .util.Arrays;
public class Comparearray {

    public static void main(String[] args) {
       int a[]={11,63,8,43};
       int b[]={63,43,11,8};
       int n = a.length; 
        int m = b.length; 
        {System.out.println(" not equal");
       boolean  ans=Arrays.equals(a,b);
       {System.out.println(" not equal");
output: equal

Thus from the above two ways, we can check whether two arrays are equal or not.

Leave a Reply

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