[Java] How to compare arrays?


I want to compare two arrays and see if they are equal, how can I do that in Java?

1 Answer

3 years ago by

Java has Arrays.equals() util method to compare two arrays. Following code show how to do that

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		String[] arr1 = { "blue", "red", "green", "yellow" };
		String[] arr2 = { "blue", "red", "green", "yellow" };
		String[] arr3 = { "blue", "red" };
		
		System.out.println(Arrays.equals(arr1, arr2));
		System.out.println(Arrays.equals(arr1, arr3));
	}
}

Output:

true
false

Try this code online here: https://onecompiler.com/java/3xmt97ra9

3 years ago by Karthik Divi