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 = [true, false, true]
Output: Both the arrays are not equal.
Method 1:
Array class in Java provides the method Arrays.equals() to check whether two arrays are equal or not.
Syntax:
public static boolean equals(boolean[] a, boolean[] a1)
Parameters:
a - one array to be tested for equality
a1 - another array to be tested for equality
Returns: It returns true if both the arrays are equal else returns false.
Code:
Java
import java.util.Arrays;
class GFG {
public static void main(String[] args)
{
boolean [] a = new boolean [] { true , true , false };
boolean [] a1 = new boolean [] { true , true , false };
System.out.println( "Array1..." );
for ( int i = 0 ; i < a.length; i++)
{
System.out.println(a[i]);
}
System.out.println( "Array2..." );
for ( int j = 0 ; j < a1.length; j++)
{
System.out.println(a1[j]);
}
boolean result = Arrays.equals(a, a1);
if (result)
{
System.out.println( "Both the arrays equal " );
}
else
{
System.out.println(
"Both the arrays not equal " );
}
}
}
|
Output
Array1...
true
true
false
Array2...
true
true
false
Both the arrays equal
Method 2:
- In this, we will use the Naive approach to compare two arrays.
- We can run a for loop and check every element of the array and compare each one of them.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
boolean [] a = new boolean [] { true , true , false };
boolean [] a1 = new boolean [] { true , true , false };
System.out.println( "Array1..." );
for ( int i = 0 ; i < a.length; i++)
{
System.out.println(a[i]);
}
System.out.println( "Array2..." );
for ( int j = 0 ; j < a1.length; j++)
{
System.out.println(a1[j]);
}
for ( int i = 0 ; i < a.length; i++)
{
if (a[i] != a1[i])
{
System.out.println(
"Both the arrays equal " );
System.exit( 0 );
}
}
System.out.println( "Both the arrays equal " );
}
}
|
Output
Array1...
true
true
false
Array2...
true
true
false
Both the arrays equal
Last Updated :
17 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...