In this example, let’s see how to compare two arrays and confirm they are equal in Java.
Source Code
package com.beginner.examples;
import java.util.Arrays;
public class CompareArray {
public static void main(String[] args) {
//Create two array object.
String[] strArray1 = {"Hi", "Hello World"};
String[] strArray2 = {"Hi", "Hello World"};
/*
* Use the method Arrays.deepEquals() to compare two arrays.
*/
boolean result1 = Arrays.deepEquals(strArray1, strArray2);
System.out.println("Compare result is : " + result1);
//Create different array.
String[] strArray3 = {"I am different array"};
boolean result2 = Arrays.deepEquals(strArray1, strArray3);
System.out.println("Compare result is : " + result2);
}
}
Output:
Compare result is : true
Compare result is : false
References
Imported packages in Java documentation: