Make Selenium Easy

#1. Java Program To Check Equality Of Two Arrays

Problem Statement

Write a Java program to check if two arrays are equal or not.

YouTube Video

If you prefer watching YouTube video for this programming question then you can refer here:-

Ask Questions

Whenever programming questions are asked in interviews especially in startups and product-based companies, the interviewer expects you to ask questions to understand problems well instead of directly jumping on writing codes. It may be one of the criteria to evaluate your candidature.

From the above statement, it is not clear if given arrays will be single or multi-dimensional and how equality is defined here. You may ask the below questions:-

  1. Will arrays be single or multidimensional?
  2. Should both arrays contain same elements in same order or same number of elements irrespective of order?

I will consider answers to the above questions below:-

  1. Arrays will be single dimensional.
  2. Both arrays should have same number of elements in the same order.

Even to be more sure you can confirm types of arrays. Just in case of negative scenarios one array may be an int while another String.

Logic Building

The next step is to think about logic. Once you get the logic you can write code.

There are already readymade methods named equals() and deepEquals() provided by class “Arrays” but in interviews, we are not allowed to use these methods.

int[] arr1 = {10,20,30,40};
int[] arr2 = {10,20,30,40};

  • Let’s take above two int arrays as example. To check equality you might be loooking at elements of both arrays but don’t you think first we should check the equality of lengths of both arrays first as that will be basic entry criteria before we go for further step.
  • If lengths of arrays are not same then why even we should go and iterate through both arrays to check equality of elements. Lengths of both arrays are not equal means arrays are not equals.
  • If lengths are matched then we should iterate arrays to match if each indexe has same elements in both arrays.
  • If at any index, elements are not equal in both arrays then we should terminate the loop then and there as there is no meaning of checking for remaining indexes as we know that both arrays are not equal.

The below flowchart can summerize above logic:-

Java Program

Now you can write Java code easily implementing above logics.


If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

1 thought on “#1. Java Program To Check Equality Of Two Arrays

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.