How to Compare Two Arrays in Java using built-in functions
In this blog, we will learn how to compare two arrays in Java using built-in functions. This will be asked in the most of the interviews. This can be implemented in the below way:
In the below snippet, we have done the following:
- Created two arrays and assigned some elements in it.
- Using built-in function Arrays.equals method we can compare our two arrays and validate them accordingly.
- Here, we have declared the two arrays differently, one with 3 elements and the other array with 4 elements
- Validating them using If statement and the built-in function as mentioned above
[java]
package Javaprograms;
import java.util.Arrays;
public class CompareArrays {
public static void main(String[] args) {
int a[] = {1,3,5};
int b[] = {1,3,4,5};
if(Arrays.equals(a, b))
{
System.out.println("Both the Arrays are EQUAL");
}
else
{
System.out.println("Both the Arrays are not EQUAL");
}
}
}
[/java]
[java]
Output:
——-
Both the Arrays are not EQUAL
[/java]
In the below snippet, we have done the following:
- using the same above arrays, But in this instance we have used the equal elements and equal values in their indices of those arrays to see the result as Equal.
[java]
package Javaprograms;
import java.util.Arrays;
public class CompareArrays {
public static void main(String[] args) {
int a[] = {1,3,5};
int b[] = {1,3,5};
if(Arrays.equals(a, b))
{
System.out.println("Both the Arrays are EQUAL");
}
else
{
System.out.println("Both the Arrays are not EQUAL");
}
}
}
[/java]
[java]
Output:
——-
Both the Arrays are EQUAL
[/java]
Please watch the Youtube video for better understanding.







