How to check If two Strings Array are equal in Java? Example Tutorial

Hello guys, if you are wondering how to check if two given String array are equal, I mean they contain same number of elements with same values and looking for solution then you have come to the right place. In the past, I have shared several coding questions on different data structures like linked list, binary tree, string, and even system design and today, we shall be working with arrays, Oh arrays are so pretty! And it’s very simple to learn. Having understood the concept of arrays the goal is to be able to check if two String arrays are equivalent. 

What is/are array(s)?

An array is a data structure in java that holds values of the same type with its length specified right from creation time. Think of a container, like the creation of eggs.

Here is another instance, Oftentimes you may have to work on a task whereby you will have to store a large number of values during the execution of a program. for instance, you need to read 50 numbers, calculate their average, and find out how many numbers are above the average, and how many numbers are below average. 

Your program first reads the numbers and calculates their average, then compares each number with the average to determine whether it is above the average or below. To accomplish this task, the numbers must all be stored in variables. 

You have to declare 50 variables and repeatedly write almost identical code 50 times. Writing a program this way would be impractical. So, how do you solve this problem? An efficient, organized approach is needed. Java and most other high-level languages provide a data structure, the array, which stores a fixed-size sequential collection of elements of the same type.

In the present case, you can store all 50 numbers into an array and access them through a single array variable.

when you are creating your array, the items coming in must be the same and you must specify how many items are coming. If you have stated that the items coming are integers, so it is and no other data type (like string, char etc) can be there and vice versa.

How do you create an array?

  1. Int [] num = new int [5];

In this previous line of code, you are creating an array of integer numbers with the variable name "num" and you are assigning it to a new integer of length 5. meaning that the items coming can only be an integer and it has to be 5. anything that does not correlate with what you have specified results to compilation error.

In an array you can access each element through its index, an index number starts from zero. So the element 1 is index num 0,2 is index num 1, 3 is index num 3, and on and on as you can see above.

If you want to get the total number of the index you will do length - 1 because the length you specified at creation time is 5 and because the indexes start from 0, not 1. so, the length of the indexes is 4.

Java Program to check if two String arrays are equal or not

So, Right now, we can proceed in solving the problem. We need to check if two strings arrays are equivalent.  Let’s go!

  1. public class StringEquality{
  2. public boolean checkEquality(String[] string1, String[] string2) {
  3. if (string1 == string2) {
  4. // both are null or booth are same instance
  5. return true;
  6. }
  7. if(string1 == null || string2 == null) {
  8. // one of the arrays is null so code bellow would fail
  9. return false;
  10. }
  11. if (string1.length == string2.length) {
  12. for (int i = 0; i < string1.length; i++) {
  13. if (!string1[i].equals(string2[i])){
  14. // equal rewritten to not equal
  15. return false;
  16. }
  17. }
  18. return true;
  19. }
  20. // no need to write else since every branch in if will result in return
  21. return false;
  22. }
  23. public class StringEqualityMain {
  24. public static void main(String[] args) {
  25. StringsEquality equality = new StringsEquality();
  26. String [] array1 = {"Ade","Boy","Cold" };
  27. String [] array2 = {"Ade","Boy","Cold" };
  28. boolean isEqual = equality.checkEquality(array1,array2);
  29. System.out.println(isEqual);
  30. }
  31. }
  32. }

Line 1 was a class declaration. And in Line 2 The method “CheckEquality” was created which takes in 2 String arrays as parameters, string 1 and 2 respectively. So, line 3 is validating if strings 1 and 2 are null, it should return true.

And in line 7, if one of the strings is null, and the other is not then it should return false. Line 11 is validating if the strings are of the same length(it would return true at line 18)then it should proceed to line 13 and loop through.

In line 14, if the index (i) of the first string is not equal to index (i) of the second string, it should return false. This is checking if each character of the first string is not equal to each character in the second string. So every other thing apart from the conditions specified returns false in line 21.

Line 23 and 24 are another class and the main method respectively, Line 25 creates an instance of the class “StringsEquality”. Line 26 and 27 initialized the first array and the second respectively, the method “checkEquality()” was called in line 28 and was assigned to a variable “isEqual”. The output was printed in line 29.


How To Check If Two Strings Array are Equivalent in Java? Example Tutorial

That's all about how to check if two String arrays are equivalent in Java or not. You can use the same approach to compare any kind of arrays in Java like array of primitive types, I mean an array of int, long, byte, short, long, and float, as well as arrays of reference types like an array of Integer, Float, and Double in Java. 

Other Java Array Tutorials and Examples you may like:
  • The ultimate guide of arrays in Java (tutorial)
  • 22 Array Concepts Interview Questions in Java (questions)
  • How to create an array from ArrayList of String in Java (tutorial)
  • 7 Best Courses to learn Data Structure and Algorithms (courses)
  • 20+ String Coding Problems from Interviews (questions)
  • How to remove duplicates from an unsorted array in Java? (solution)
  • 20+ array-based coding problems from Interviews (Questions)
  • 10 Data Structure Courses to Crack Programming Interviews (courses)
  • 20+ binary tree-based coding problems (questions)
  • How to find all pairs whose sum is equal to a given number in an array? (solution)
  • How to reverse an array in place in Java? (solution)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 10 Free Data Structure and Algorithm Courses for Beginners (courses)
  • Top 20 Searching and Sorting Interview Questions (questions)
  • How to make a binary search tree in Java? (solution)
  • 50+ Data Structure and Algorithms Interview Questions (questions)

Thanks for reading this article so far. If you like this ultimate Java Array tutorial and examples then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses to start with.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.