Методы string array java

Java String Array

Java String Array

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • Java String array is basically an array of objects.
  • There are two ways to declare string array — declaration without size and declare with size.
  • There are two ways to initialize string array — at the time of declaration, populating values after declaration.
  • We can do different kind of processing on string array such as iteration, sorting, searching etc.

Let’s go over java string array example programs now.

Java String Array Declaration

Below code snippet shows different ways for string array declaration in java.

String[] strArray; //declare without size String[] strArray1 = new String[3]; //declare with size 

Note that we can also write string array as String strArray[] but above shows way is the standard and recommended way. Also in the above code, strArray is null whereas strArray1 value is [null, null, null] .

Читайте также:  Can java be installed on android

Java String Array Initialization

Let’s look at different ways to initialize string array in java.

//inline initialization String[] strArray1 = new String[] ; String[] strArray2 = ; //initialization after declaration String[] strArray3 = new String[3]; strArray3[0] = "A"; strArray3[1] = "B"; strArray3[2] = "C"; 

All the three string arrays will have same values. However if you will call equals method on them, it will return false.

System.out.println(strArray1.equals(strArray2)); // false System.out.println(Arrays.toString(strArray1).equals(Arrays.toString(strArray2)));// true 

The reason is that array are Objects and Object class implements equals() method like below.

public boolean equals(Object obj)

Second statement is true because when converted to String, their values are same and String class equals() method implementation check for values. For more details, please check String class API documentation.

Iterating over java string array

We can iterate over string array using java for loop or java foreach loop.

String[] strArray2 = ; for (int i = 0; i < strArray2.length; i++) < System.out.print(strArray2[i]); >for (String str : strArray2)

Search for a String in the String array

We can use for loop to search for an string in the array, below is a simple example for that.

package com.journaldev.stringarray; public class JavaStringArrayExample < public static void main(String[] args) < String[] strArray = < "A", "B", "C" >; boolean found = false; int index = 0; String s = "B"; for (int i = 0; i < strArray.length; i++) < if(s.equals(strArray[i])) < index = i; found = true; break; >> if(found) System.out.println(s +" found at index "+index); else System.out.println(s +" not found in the array"); > > 

Notice the use of break keyword to get out of the loop as soon as we found the string.

Java String Array Sorting

We can implement our own sorting algorithm, or we can use Arrays class sorting method.

String[] vowels = ; System.out.println("Before sorting "+Arrays.toString(vowels)); Arrays.sort(vowels); System.out.println("After sorting "+Arrays.toString(vowels)); 

Output of above code snippet will be:

Before sorting [a, i, u, e, o] After sorting [a, e, i, o, u] 

Note that String implements Comparable interface, so it works for natural sorting. Incase you want to sort by some other way, you can use Arrays.sort() overloaded method by passing a Comparator. Learn about these sorting techniques at Comparable and Comparator in java.

Convert String to String Array

We can convert String to string array using it’s split() method. It’s useful when you get a single string as input with values separated using delimiter character.

String str = "a,e,i,o,u"; String[] vowels = str.split(","); System.out.println(Arrays.toString(vowels)); //[a, e, i, o, u] 

Convert String Array to String

We can use Arrays.toString() method to convert String array to String. Note that array doesn’t implement toString() method, so if you will try to get it’s string representation then you will have to rely on Arrays class, or else write your own custom code.

String[] vowels = < "a", "e", "i", "o", "u" >; System.out.println(vowels); System.out.println(Arrays.toString(vowels)); 

Output will be like below.

[Ljava.lang.String;@3d04a311 [a, e, i, o, u] 

The first output is because of Object class toString() implementation like below.

Java String Array to List

We can get a list representation of string array using Arrays.toList() method. Note that this list is backed by the array and any structural modification will result in java.lang.UnsupportedOperationException .

String[] vowels = < "a", "e", "i", "o", "u", "a", "o" >; List vowelsList = Arrays.asList(vowels); System.out.println("vowelsList = "+vowelsList); //vowelsList.add("x"); //java.lang.UnsupportedOperationException vowelsList.set(0, "x"); //allowed because no structural modification System.out.println("vowelsList = "+vowelsList); 

That’s all for java string array. Reference: Arrays Oracle Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

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:

Источник

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