The Wayback Machine - https://web.archive.org/web/20240910192104/https://www.geeksforgeeks.org/java-program-to-check-if-two-arrays-are-equal-or-not/
Open In App

Java Program to Check if two Arrays are Equal or not

Last Updated : 15 Oct, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain the same set of elements and in the same order. 

Note: If there are repetitions, then counts of repeated elements should be the same for two arrays to be equal.

Examples:

Input  : arr1[] = {1, 2, 5, 4, 0};
         arr2[] = {1, 2, 5, 4, 0}; 
Output : Yes

Input  : arr1[] = {1, 2, 5, 4, 0, 2};
         arr2[] = {2, 4, 5, 0}; 
Output : No
 
Input : arr1[] = {1, 7, 7};
        arr2[] = {7, 7, 1};
Output : No

Method 1: Using the pre-defined method

  • First, we will initialize two arrays and will insert the elements in both the arrays.
  • After that, Arrays.equal() function is called to check whether the two arrays are equal or not and the result will be stored into one boolean variable namely result.
  • Finally, the result will be printed.

Example: Below is the implementation of the above approach. 

Java




// Java Program to find the if the arrays are equal
  
import java.util.Arrays;
  
public class CheckArraysEqual {
    public static void main(String[] args)
    {
        // Initializing the first array
        int a[] = { 30, 25, 40 };
  
        // Initializing the second array
        int b[] = { 30, 25, 40 };
  
        // store the result
        // Arrays.equals(a, b) function is used to check
        // whether two arrays are equal or not
        boolean result = Arrays.equals(a, b);
  
        // condition to check whether the
        // result is true or false
        if (result == true) {
            // Print the result
            System.out.println("Two arrays are equal");
        }
        else {
            // Print the result
            System.out.println("Two arrays are not equal");
        }
    }
}


Output

Two arrays are equal

Example 2:

Java




// Java Program to find the if the arrays are equal
  
import java.util.Arrays;
  
public class CheckArraysEqual {
    public static void main(String[] args)
    {
        // Initializing the first array
        int a[] = { 30, 25, 40, 23 };
  
        // Initializing the second array
        int b[] = { 30, 26, 40 };
  
        // store the result
        // Arrays.equals(a, b) function is used to check
        // whether two arrays are equal or not
        boolean result = Arrays.equals(a, b);
  
        // condition to check whether the
        // result is true or false
        if (result == true) {
            // Print the result
            System.out.println("Two arrays are equal");
        }
        else {
            // Print the result
            System.out.println("Two arrays are not equal");
        }
    }
}


Output

Two arrays are not equal

Time Complexity : O(n)
Auxiliary Space : O(1)

Method 2: Without using pre-defined function

  • First, we will initialize two arrays a and b and insert the elements in both the arrays. Then create a boolean variable called result to store the result after checking.
  • Then we will check the length of the arrays whether the length of the arrays are equal or not.
  • If it is equal then, loop will repeat for every element till the end of the array. If somewhere some element is not equal then we will make the result as false.
  • If the value of the result variable is false, it means the arrays are not equal.
  • If the arrays are equal then the value of the result variable will remain true.
  • And also if the length of the arrays is not equal it will return false.

Example 1: Below is the implementation of the above approach.

Java




// Java Program to check if the arrays are equal
  
public class checkArraysEqual {
    public static void main(String[] args)
    {
        // Initializing the first array
        int a[] = { 10, 30, 12 };
        // Initializing the second array
        int b[] = { 10, 30, 12 };
  
        // store the result
        boolean result = true;
  
        // Check if length of the two arrays are equal or
        // not
        if (a.length == b.length) {
            
            // Loop to check elements of arrays one by one
            for (int i = 0; i < a.length; i = i + 1) {
                
                // To check if any element is different
                if (a[i] != b[i]) {
                    
                    // If any element is different then it
                    // will assign false into boolean
                    // variable
                    result = false;
                }
            }
        }
        else {
            
            // If the length of two arrays is
            // different then it will assign
            // false into boolean variable
            result = false;
        }
        
        // After completion to check whether
        // result is true of false
        if (result == true) {
            
            // Print the result
            System.out.println("Arrays are equal");
        }
        else {
            
            // Print the result
            System.out.println("Arrays are not equal");
        }
    }
}


Output

Arrays are equal

Example 2: 

Java




// Java Program to check if the arrays are equal
  
public class checkArraysEqual {
    
    public static void main(String[] args)
    {
        // Initializing the first array
        int a[] = { 10, 30, 12 };
        // Initializing the second array
        int b[] = { 45, 50, 55, 60, 65 };
  
        // stores the result
        boolean result = true;
  
        // Check if length of the two arrays are equal or
        // not
        if (a.length == b.length) {
            
            // Loop to check elements of arrays one by one
            for (int i = 0; i < a.length; i = i + 1) {
                
                // To check if any element is different
                if (a[i] != b[i]) {
                    
                    // If any element is different then it
                    // will assign false into boolean
                    // variable
                    result = false;
                }
            }
        }
        else {
            
            // If the length of two arrays is different then
            // it will assign false into boolean variable
            result = false;
        }
        
        // After completion to check whether result is true
        // of false
        if (result == true) {
            
            // Print the result
            System.out.println("Arrays are equal");
        }
        else {
            // Print the result
            System.out.println("Arrays are not equal");
        }
    }
}


Output

Arrays are not equal

Time Complexity : O(n)
Auxiliary Space : O(1)



Previous Article
Next Article

Similar Reads

Check if Two Integers are Equal or Not in Java
Checking two integers equal or not in Java is done by various approaches. Arithmetic operatorComparison OperatorsString functionsXOR operatorComplement (~) and bit-wise (&amp;) operator Example Input: FirstNumber = 15 SecondNumber= 15 Output: Numbers are same Input: FirstNumber = 15 SecondNumber= 25 Output: Numbers are not same Approach #1: Arithme
3 min read
Java Program for Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
Java Program to Check if two numbers are bit rotations of each other or not
Given two positive integers x and y, check if one integer is obtained by rotating bits of other. Input constraint: 0 &lt; x, y &lt; 2^32 Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.More information on bit rotation can be found hereExample 1
3 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
Java Program to Find the closest pair from two sorted arrays
Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. We are given two arrays ar1[0...m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] - x) is minimum. Example: Input: ar1[] = {1, 4, 5, 7}; ar2[] = {10, 20
3 min read
Java Program to Compare two Boolean Arrays
Two arrays are equal if they contain the same elements in the same order. In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is .equals() method.By using the Naive approach. Examples: Input : A = [true , true , false] A1 = [true, true, false] Output: Both the arrays are equal. Input : A = [true, true, false] A1
3 min read
Java Program to Compare two Double Arrays
Java double array is used to store double data type values only. The default value of the elements in a double array is 0. We can compare two double arrays by two ways: By naive approach of traversing through the whole array and comparing each element.By Arrays.equals() method. Method 1: Naive Approach By Comparing one element at a time by traversi
2 min read
Java Program to Compare two Float Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.The base value is index 0 and the difference between the two indexes is the offset. In this program, we need to compare two arrays having elements of float type. Two arrays are equal if they contain the same element
3 min read
Java Program to Find k pairs with smallest sums in two arrays
Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] Explanation: The first 3 pairs are returned from th
3 min read
Java Program to Print uncommon elements from two sorted arrays
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements are present in both arrays. Input : arr1[] = {10, 20
2 min read
Java Program for Median of two sorted arrays of same size
Write a Java program for a given 2 sorted arrays A and B of size n each. the task is to find the median of the array obtained by merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)). Examples: Input: ar1[] = {1, 12, 15, 26, 38} ar2[] = {2, 13, 17, 30, 45}Output: 16Explanation:After merging two arrays, we get {1, 2
6 min read
Java Program to Merge Two Arrays
Given two arrays, the task is to merge or concatenate them and store the result into another array. Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}Output: arr3[] = {1, 3, 4, 5, 2, 4, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Output: arr3[] = {5, 8, 9, 4, 7, 8} Method 1: Using Predefined functionFirst, we initialize two arra
6 min read
Java Program to Find Common Elements Between Two Arrays
Given two arrays and our task is to find their common elements. Examples: Input: Array1 = ["Article", "for", "Geeks", "for", "Geeks"], Array2 = ["Article", "Geeks", "Geeks"]Output: [Article,Geeks] Input: Array1 = ["a", "b", "c", "d", "e", "f"], Array2 = ["b", "d", "e", "h", "g", "c"]Output: [b, c, d, e] Using Iterative Methods Approach: Get the two
4 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Java Program to Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples:  Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest proper prefix which is also suffix) construct
2 min read
Java Program to Check if a Directory is Empty or Not
The list() method defined in class java.io.File which is used to obtain the list of files and folders(directories) present in the specified directory defined by its pathname. The list of files is stored in an array of string. If the length of an array is greater than 0, then the specified directory is not empty, else it is empty. Method 1: Use of l
3 min read
Java Program to Check Whether a Matrix is Symmetric or Not
A symmetric matrix is a square matrix in which the transpose of the square matrix is the same as the original square matrix. A square matrix is a matrix in which the number of columns is the same as the number of rows. If the matrix is a symmetric matrix then it is also a square matrix but vice versa isn't true. Matrix is simply considered as 2D ar
4 min read
Java Program to Check If a Number is Neon Number or Not
A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range. Illustration: Case 1: Input : 9 Output : Given number 9 is Neon number Explanation : square of 9=9*9=81; sum of digit of square : 8+1=9(which is equal to given number) Case 2: Input : 8 Output
4 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Java Program to Check If a Number is Spy number or not
A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time. Example: Input : 22 Output: Given number is a SPY number. Explanation: Sum of the number is 4 (2 + 2) Product of the number is as 4 (2 * 2) Input : 1241 Ou
2 min read
Java Program to check if strings are rotations of each other or not
Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false)Algorithm: areRotations(str1, str2) 1. Create a temp string and store concatenation of str1 to str1 in temp. temp = str1.str1 2. If str2 is a substring of temp then s
2 min read
Java Program to Check if a given matrix is sparse or not
A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4
2 min read
Check if two arrays are permutations of each other
Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1}Output: YesInput: arr1[] = {2, 1, 3, 5,} arr2[] = {3, 2, 2, 4}Output: NoWe strongly recommend you to minimize your browser and try
15+ min read
Java Program to Check the Multiplicability of Two Matrices
Given two matrices, the task to check Multiplicability of them. Matrices can either be square or rectangular. Matrices must have the same datatype. Multiplicablity of the matrix depends on their ROWS and COLUMNS. If the Columns of the first matrix are equal to the Rows of the second matrix then both the matrices are multiplicable. Example: Input :
2 min read
Java Program to Check if Two of Three Boolean Variables are True
Boolean values are true/false. In this program, we need to check if any two out of three boolean values are true or not. We will be discussing two major approaches to do it: using an if-else.using the ternary operator. Approach 1: Using if-else condition We initialize three boolean variable flags, with either a boolean FALSE or a TRUE value. The co
3 min read
Java Program for Check if given string can be formed by two other strings or their permutations
Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pair from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" which can be rearranged as "amazon". Input: str = "gee
4 min read
Java Program to Check Armstrong Number between Two Integers
A positive integer with digits p, q, r, s…, is known as an Armstrong number of order n if the following condition is fulfilled. pqrs... = pn + qn + rn + sn +....Example: 370 = 3*3*3 + 7*7*7 + 0 = 27 + 343 + 0 = 370Therefore, 370 is an Armstrong number. Examples: Input : 100 200 Output :153 Explanation : 100 and 200 are given two integers. 153 = 1*1
2 min read
Java Program To Check If Two Linked Lists Are Identical
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1-&gt;2-&gt;3) and b(1-&gt;2-&gt;3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method
3 min read
Java Program To Check Whether Two Strings Are Anagram
Write a function to check whether two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. Program to Check Two Strings Are Anagram Of Each Other in JavaBelow is the Prog
8 min read
How to Convert Two Arrays Containing Keys and Values to HashMap in Java?
HashMap is part of the Collections framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys or the key-value pairs can be accessed using their indexes (of Integer type). HashMap is similar to Hashtable in java. The main difference between HashTable and HashMap i
2 min read
Practice Tags :