19 Aug How to Compare two Byte Arrays in Java
The Byte array in Java is an 8-bit signed two’s complement integer with minimum value -128 and maximum 127. To compare two-byte arrays, Java has a built-in method Arrays.equal(). It checks for the equality of two arrays.
Syntax
static boolean equals(byte[] arr1, byte[] arr2)
Above, returns TRUE if both the arrays are equal.
The method Arrays.equals() compares on the basis of count of elements and the corresponding pairs of elements.
Let us see some examples to compare Byte arrays;
Example 1
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
byte[] arr1 = new byte[] { 2, 5, 7, 8, 10 };
byte[] arr2 = new byte[] { 2, 5, 7, 8, 10 };
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 byte arrays are equal = "+Arrays.equals(arr1, arr2));
}
}
Output
Array1... 2 5 7 8 10 Array2... 2 5 7 8 10 Both the byte arrays are equal = true
Example 2
Let us now see another example in which the arrays are same, but the order of elements is different:
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
byte[] arr1 = new byte[] { 10, 15, 40, 30 };
byte[] arr2 = new byte[] { 10, 15, 30, 40 };
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 boolean arrays are equal = "+Arrays.equals(arr1, arr2));
}
}
Output
Array1... 10 15 40 30 Array2... 10 15 30 40 Both the byte arrays are equal = false
No Comments