Java – Slice an Array
To check if two Arrays are equal in Java, call Arrays.equals() method and pass the two arrays as arguments. Arrays.equals() returns boolean value of true if given two arrays are equal, or false if not.
Examples
In the following example, we take two integer arrays: arr1 and arr2, and check if these two arrays are equal using Arrays.equals() method.
Main.java
</>
Copy
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int arr1[] = {2, 4, 6, 8};
int arr2[] = {2, 4, 6, 8};
if (Arrays.equals(arr1, arr2)) {
System.out.println("Arrays are equal.");
} else {
System.out.println("Arrays are not equal.");
}
}
}
Output
Arrays are equal.
Now, let us take different value in arrays: arr1 and arr2, and check if these two arrays are equal using Arrays.equals() method. Arrays.equals() should return false.
Main.java
</>
Copy
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int arr1[] = {2, 4, 6, 8};
int arr2[] = {3, 6, 9};
if (Arrays.equals(arr1, arr2)) {
System.out.println("Arrays are equal.");
} else {
System.out.println("Arrays are not equal.");
}
}
}
Output
Arrays are not equal.
Conclusion
In this Java Tutorial, we learned how to check if two Arrays are equal in Java using Arrays.equals() method with examples.