Compare two Boolean Arrays in Java

The Boolean arrays in Java stores Boolean datatypes i.e. the boolean values, TRUE and FALSE. To compare two boolean array, Java has a built-in method Arrays.equal(). It checks for the equality of two arrays.

Syntax

static boolean equals(boolean[] arr1, boolean[] arr2)

Above, returns TRUE if both the arrays are equal.

The method Arrays.equals() compares in the basis of count of elements and the corresponding pairs of elements.

Let us see some examples to compare Boolean arrays;

Example 1

import java.util.Arrays;

public class Example {

  public static void main(String[] args) {
   
     boolean[] arr1 = new boolean[] { false, false, true };
     boolean[] arr2 = new boolean[] { false, false, true };
     
     System.out.println("Array1...");
     for (int i = 0; i < arr1.length; i++) {
       System.out.println(arr1[i]);
     }

     System.out.println("Array2...");
     for (int j = 0; j < arr2.length; j++) {
       System.out.println(arr2[j]);
     }
     
     System.out.println("Both the arrays equal = "+Arrays.equals(arr1, arr2));
  }
}

Output

Array1...
false
false
true
Array2...
false
false
true
Both the arrays equal = True

Example 2

Let us now see another to compare two Boolean arrays, in which the arrays are same, but the order is different:

import java.util.Arrays;

public class Example {

  public static void main(String[] args) {
   
     boolean[] arr1 = new boolean[] { true, true, true, false };
     boolean[] arr2 = new boolean[] { true, false, true, true };
     
     System.out.println("Array1...");
     for (int i = 0; i < arr1.length; i++) {
       System.out.println(arr1[i]);
     }

     System.out.println("Array2...");
     for (int j = 0; j < arr2.length; j++) {
       System.out.println(arr2[j]);
     }
     
     System.out.println("Both the arrays equal = "+Arrays.equals(arr1, arr2));
  }
}

Output

Array1...
true
true
true
false
Array2...
true
false
true
true
Both the arrays equal = false
Java Program for String representation of Boolean
Java Program to convert integer to boolean
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment