Syntax error Java Program to compare two Byte Arrays

Java Program to compare two Byte Arrays



To compare two Byte Arrays, use the Arrays.equals() method. Here we have declared and initialized a total of 4 arrays.

byte[] arr1 = new byte[] { 11, 13, 30, 45, 77, 89 };
byte[] arr2 = new byte[] { 12, 13, 34, 87, 99, 33};
byte[] arr3 = new byte[] { 11, 13, 30, 45, 77, 89 };
byte[] arr4 = new byte[] { 13, 16, 56, 78, 98, 99 };

Now, using the Arrays.equals() method, we will be compare two arrays.

Arrays.equals(arr1, arr2);

In the same way, other arrays would be compared one by one.

Let us see the complete example to compare two Byte Arrays.

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      byte[] arr1 = new byte[] { 11, 13, 30, 45, 77, 89 };
      byte[] arr2 = new byte[] { 12, 13, 34, 87, 99, 33};
      byte[] arr3 = new byte[] { 11, 13, 30, 45, 77, 89 };
      byte[] arr4 = new byte[] { 13, 16, 56, 78, 98, 99 };
      System.out.println("Array1 is equal to Array2 = "+Arrays.equals(arr1, arr2));
      System.out.println("Array1 is equal to Array3 = "+Arrays.equals(arr1, arr3));
      System.out.println("Array1 is equal to Array4 = "+Arrays.equals(arr1, arr4));
      System.out.println("Array2 is equal to Array3 = "+Arrays.equals(arr2, arr3));
   }
}

Output

Array1 is equal to Array2 = false
Array1 is equal to Array3 = true
Array1 is equal to Array4 = false
Array2 is equal to Array3 = false
Updated on: 2020-06-26T10:21:03+05:30

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements