CodeGym/Java Blog/Java Arrays/String Array in Java
Author
John Selawsky
Senior Java Developer and Tutor at LearningTree

String Array in Java

Published in the Java Arrays group
members
Often the first data structure a novice programmer gets acquainted with is an array. That's because arrays are fairly easy to learn. A one-dimensional array is a sequence that consists of a fixed number of cells in which data can be stored. In the case of the Java language, you can store only one type of data in an array. In other words, arrays in Java are homogeneous. Array cells can contain objects of any type. You can put objects of any type, primitive or object, into an array. Today we are going to look at string arrays in Java language, that is, arrays, each element of which is a string. We'll figure out how to declare Java String Array and how to work with it.

How to declare and initialize a String Array

You can declare and initialize a String array in Java in different ways. For example like in code below:
String[] myArray = {"value1", "value2", "value3"};
Here we first declare a variable myArray of type String[]. Then later, we initialize the array with three string values enclosed in curly braces. Alternatively, you can have String array declaration and initialization on separate lines:
String[] myArray; // String array declaration
myArray = new String[] {"value1", "value2", "value3"}; // initialize the array
Here we have the same result as the first code snippet but separate the declaration and initialization into two steps. Also, you can initialize an array with size only, just like here below:
String[] myArray = new String[5];
Here you create a String array and specify the size of String Array, but you don't provide any initial values. You can then assign values to the array using a loop or by specifying the values individually. Note that in all cases, you have to specify the type of the array (in this case, String) while declaring the variable.

How to iterate through the String array

In Java you can iterate through a String array using a loop. It could be for or a foreach construction. Let’s have an example that uses both types of loops:
public class IterateStringArrayExample {
    public static void main(String[] args) {
        String[] stringArray = {"violin", "viola", "cello", "double bass"};

        // Using a for loop
        for (int i = 0; i < stringArray.length; i++) {
            String s = stringArray[i];
            System.out.print(s + " ");
        }
        System.out.println();

        // Using a foreach loop
        for (String s : stringArray) {
            System.out.print(s + " ");
        }
        System.out.println();
    }
}
Here we first create a String array named stringArray with four elements (String musical instruments). Then, both loops iterate through each element of the string array and print it to the console. The foreach loop is a more concise way of iterating through an array, but the for loop can be useful if you need to access the index of each element. The output of this program will be:
violin viola cello double bass violin viola cello double bass

How to add a new element to Array

You can’t just add a new element to an array in Java. However Java has special tricks for it. If you’ve got an array of strings and need to add a new string to the end of your array, use the Arrays.copyOf method. This method creates a new array with one extra element, and then adds the new element to the end of the new array. Here's an example:
//add string Array and a new element
String[] oldArray = {"violin", "viola", "cello"};
String newElement = "double bass";
String[] newArray = Arrays.copyOf(oldArray, oldArray.length + 1);
newArray[newArray.length - 1] = newElement;
Here the Arrays.copyOf method creates a new array named newArray with a length one greater than the oldArray. The method adds newElement to the end of the newArray by assigning it to the last element of the newArray. Arrays in Java have a fixed length, so you can't add or remove elements from an array once it's been created. To dynamically add or remove elements from a collection, you'd better use another data structure. For example, a List or a Map.

How to sort elements in String Array

Sure, if you are interested in good programming exercises, you can write your sorting algorithm for the sorting procedure. However, in real working tasks it's much easier to use the Arrays.sort() method. Here's an example:
import java.util.Arrays;

public class SortStringArrayExample {
    public static void main(String[] args) {
        String[] stringArray = {"violin", "viola", "cello", "double bass"};

        // Sorting the array
        Arrays.sort(stringArray);

        // Printing the sorted array
        for (String s : stringArray) {
            System.out.print(s + " ");
        }
    }
}
Here we first create a String array named stringArray with four elements. We then call the Arrays.sort() method to sort the elements in the array in ascending order. Finally, we iterate through the sorted array using a for-each loop and print each element to the console. The output of this program is next:
cello double bass viola violin
As you can see, the method sorted elements in the stringArray alphabetically.

How to search a particular String in String array

To search for a needed String in a String array in Java, you can use a loop for iterating through each array element and compare it to the String you're searching for. Here's an example program:
public class SearchString {

       public static void main(String[] args) {
           String[] stringArray = {"violin", "viola", "cello", "double bass"};
           String searchString1 = "cello";
           String searchString2 = "piano";
           search(stringArray, searchString1);
           search(stringArray, searchString2);

       }
          public static boolean search (String[] myArray, String myString){

           boolean found = false;

           // Loop through the array to search for the string
           for (String s : myArray) {
               if (s.equals(myString)) {
                   found = true;
                   break;
               }
           }

           // Print the result
           if (found) {
               System.out.println(myString + " found in the array.");
           } else {
               System.out.println(myString + " not found in the array.");
           } return found;
       }
}
Here we're creating a method with two arguments, an array and a string to be found. We create a boolean 'found' to track whether we found the String. It is the found value that the method will return. We then use a for-each loop to iterate over each array element. We use the equals() method in the loop to compare the current element with the search string. If the method finds a match, we set it to true and use the break statement to break out of the loop early. Finally, we print the result depending on whether the found is true or false. In the main method, we call the search method twice, with the String that is in the array and the one that is not. The output of this program is next:
cello found in the array. piano not found in the array.

How to convert String Array to String

You can use the String.join() method to convert a String array to String in Java. This method returns a string concatenated by the given delimiter. The delimiter is copied for each element in the String join() method. String Array in Java - 1Here's an example:
String[] myArray = {"value1", "value2", "value3"};
String joinedString = String.join(", ", myArray);
System.out.println(joinedString);
The output is the following:
value1, value2, value3
First, we declare a string array myArray with three string values. We then use the String.join() method to join all array elements into a single string. The first argument to String.join() is the delimiter you want to use between each array element. We've used "," (a comma followed by a space) as the delimiter. The second argument is the array that you want to join. Finally, we assign the resulting String to the variable joinedString and print it to the console.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet