How to Compare Arrays in Java



Java



In this article, we show how to compare arrays in Java.

When we want to compare the individual elements of 2 arrays, we don't use the == operator. This is because with the == operator, the array variables are considered to be equal only if both variables point to exactly the same array instance. This is usually not what is desired.

To compare 2 arrays element by element, Arrays.equal method should be used instead.

Comparing Arrays

To compare 2 arrays in Java, we use the Arrays.equal() and instead of the parentheses, put the arrays we want to compare.

So if we want to compare array1 and array2 (representing 2 arrays), the statement, Arrays.equal(array1, array2).

The code below shows how to do this.



So this is all that is required to compare arrays in Java.

We create 2 arrays of type string and set them equal to "Peter" and "John" as the 2 elements.

We then create an if statement. Inside of the if statement, we place, Arrays.equal(array1, array2).

Since the 2 arrays contain the same elements (Peter and John), the if statement evaluated to true and the statement, "The 2 arrays are equal" will output.

Java Output

The 2 arrays are equal


If you make the arrays contain different elements, then you'll see that the if statement evaluates to false. So, using the above code, the statement, "The 2 arrays are equal" will not print. Nothing will print (unless you put an else statement in the code to output a statement).

HTML Comment Box is loading comments...