18 Aug 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
1 2 3 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Array1... true true true false Array2... true false true true Both the arrays equal = false |
No Comments