Java array string equals

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.

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?

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!

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.

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.

  • 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)

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.

Источник

Java String Array

Few points to note about the above ways of string array declaration:

  • When string array is declared without size, its value is null.
  • When we declare a string array with size, the array is also initialized with null values.
  • We can also declare a string array as String strArray3[] but the above approach is recommended because it’s following convention and follows the best practice.

Java String Array Declaration

How to Initialize String Array in Java?

There are two ways to initialize a string array.

  1. Declaration and Initialization at the same time. It’s also called inline initialization.
  2. Declaring the string array and then populate the values one by one.
// inline declaration and initialization String[] fruits = new String[] < "Apple", "Banana", "Guava" >; // shortcut method to declare and initialize at the same time String[] cities = < "Cupertino", "Bangalore" >; // first declare and then populate values one by one String companies[] = new String[3]; companies[0] = "Apple"; companies[1] = "Google"; companies[2] = "Microsoft";

How to check if two String Arrays are Equal?

We use equals() method to check if two objects are equal or not. Let’s see what happens with the equals() method when we have two string arrays with the same content.

jshell> String[] a1 = a1 ==> String[2] < "1", "2" >jshell> String[] a2 = a2 ==> String[2] < "1", "2" >jshell> a1.equals(a2) $5 ==> false jshell>

The reason for the output “false” is that string array is an object. And Object class implements equals() method like this:

public boolean equals(Object obj)

Since both the arrays are referring to different objects, the output is false.

So, how to compare two string arrays for equality?

  • We can use Arrays.toString() method to convert string array to string. Then use the equals() method to check equality. This method will make sure that both the arrays have same strings at the same positions.
jshell> Arrays.toString(a1).equals(Arrays.toString(a2)) $6 ==> true

Iterating over Java String Array

We can iterate over the elements of string array using two ways.

String[] fruits = new String[] < "Apple", "Banana", "Guava" >; // recommended for Java 8 or higher version for (String fruit : fruits) < System.out.println(fruit); >// old approach, for below java 8 versions for (int i=0; i

How to search a String in the String Array?

We can use for loop to search for a string in the string array. Here is a simple program to find the indexes of the string in a string array.

package net.javastring.strings; import java.util.ArrayList; import java.util.List; public class JavaStringArray < public static void main(String[] args) < String[] vowels = new String[] < "A", "E", "I", "O", "U", "O", "E" >; System.out.println(findFirstIndex("E", vowels)); System.out.println(findAllIndexes("E", vowels)); > public static int findFirstIndex(String str, String[] array) < for (int i = 0; i < array.length; i++) < if (str.equals(array[i])) return i; >return -1; > public static List findAllIndexes(String str, String[] array) < ListindexesList = new ArrayList<>(); for (int i = 0; i < array.length; i++) < if (str.equals(array[i])) indexesList.add(i); >return indexesList; > >

Java String Array Search

Java String Array Length

We can use length attribute of the array to find the length of the string array.

jshell> String[] vowels = new String[] < "A", "E", "I", "O", "U">vowels ==> String[5] < "A", "E", "I", "O", "U" >jshell> vowels.length $8 ==> 5

Java String Array Length

Java String Array to String

We can convert string array to string using Arrays.toString() method.

jshell> String[] vowels = new String[] < "A", "E", "I", "O", "U">vowels ==> String[5] < "A", "E", "I", "O", "U" >jshell> Arrays.toString(vowels); $10 ==> "[A, E, I, O, U]" jshell> System.out.println(Arrays.toString(vowels)); [A, E, I, O, U]

Java String Array To String

Did you thought what happens when we try to print the string array directly?

Let’s see with a simple example.

jshell> String[] chars = chars ==> String[2] < "A", "B" >jshell> System.out.println(chars) [Ljava.lang.String;@28c97a5

The reason for the output is that the Object class toString() method is used to get the string representation of the array. The implementation is like this:

Now it’s clear why the output is of no use to us. Always use Arrays.toString() method to convert an array to its string representation.

Java String Array to List

We can use Arrays.asList() method to convert string array to the list of string.

jshell> String[] countries = new String[] < "USA", "UK", "INDIA">; countries ==> String[3] < "USA", "UK", "INDIA" >jshell> List countriesList = Arrays.asList(countries); countriesList ==> [USA, UK, INDIA]

Java String Array To List

Sorting a String Array

We can use Arrays.sort() or Arrays.parallelSort() method to sort a string array.

jshell> String[] countries = new String[] < "USA", "UK", "INDIA" >; countries ==> String[3] < "USA", "UK", "INDIA" >jshell> Arrays.parallelSort(countries); jshell> System.out.println(Arrays.toString(countries)); [INDIA, UK, USA]

The strings are sorted in their natural order i.e. lexicographically. We can pass a Comparator to define our own sorting logic. Here is a simple example to sort the string array in reverse order.

String[] vowels = new String[] < "A", "E", "I", "O", "U" >; Arrays.parallelSort(vowels, (String s1, String s2) -> -s1.compareTo(s2)); System.out.println(Arrays.toString(vowels));

Sorting String Array In Java

Converting String to String Array

We can use the String class split() method to convert a string into a string array. One of the popular use cases is to convert a CSV string to the string array.

jshell> String csvData = "1,2,3,4,5"; csvData ==> "1,2,3,4,5" jshell> String[] datas = csvData.split(","); datas ==> String[5] < "1", "2", "3", "4", "5" >jshell> System.out.println(Arrays.deepToString(datas)); [1, 2, 3, 4, 5]

References:

Источник

Оцените статью