String array in Java

This Java String Array article explains how to Declare, Initialize, and Create String Arrays in Java and various conversions that may be performed on String Array. In Java, arrays are a common data structure for storing many data types, ranging from elementary to user-defined. We will not cover the fundamentals of arrays and some of the most common operations performed on them.

What is a string array in Java?

An array with strings as its elements is possible. As a result, a String Array can be defined as an array containing many strings or string values. In Java, a string array is one of the most often used structures. Remember that Java’s ‘main’ method takes a String Array as an input.

A string array is a collection of things. Each element is a String. As you well know, a String is an object in Java. On a String array, you can perform any operations such as sorting, adding an element, joining, dividing, searching, etc.

In this article, we’ll go over the string array in Java in-depth and the many operations and conversions that may be performed.

Declaration of a string array

The two main ways of declaring a String Array in Java include: with or without a size specification. The two methods for declaring a String Array are listed below.

String[] arrayVar ;   // declaring a string array without size
String[] arrayVar = new String[5];// Declaration of a string array with size

A String Array is declared as a regular variable with no size in the first declaration. It’s worth noting that you’ll have to create this array with new ones before utilizing it.

A String Array is declared and instantiated in the second declaration using new. A five-element String array named ‘arrayVar’ is declared here. Because the array is not initialized, if you print the items of this array directly, you will see all of the null values. Let’s make a program that explains how to declare a String Array.

public class Codeunderscored
{
    public static void main(String[] args) {
         
        String[] arrayVarOne ;   // declaring a string array without size
        String[] arrayVarTwo = new String[5];// Declaration of a string array with size
 
        //System.out.println(myarray[0]);   //variable arrayVar might not have been initialized
        //show second array elements
        System.out.print(arrayVarTwo[0] + " " +arrayVarTwo[1]+ " " + arrayVarTwo[2]+ " " +
        arrayVarTwo[3]+ " " +arrayVarTwo[4]);
    }
}

The program above demonstrates two methods for declaring a String Array. The initial declaration, as previously stated, is devoid of size and instantiation. As a result, you’ll need to try something with ‘new’ to create this array before utilizing it. The array arrayVarOne is used without instantiating in the given program, resulting in a compiler error (commented statement).

The size is the subject of the second declaration. As a result, when the values of individual String array items are written, they are null because the array was not populated.

Setting up a string array

After you’ve declared the String Array, you’ll need to fill it with some data. Otherwise, null values are assigned to String elements as default values. As a result, after declaring the array, we proceed to initialize it.

A String array can be initialized inline with the declaration or after it has been declared. Let’s look at how to initialize a String array inline first.

String[] numArrayVar = {"one", "two", "three"};
String[] strArrayVar = new String[] {"one", "two", "three", "four"};

The initializations in the String Array above are inline initializations. The String Array is declared and initialized at the same time. You may also use the following code to create a String Array:

String[] strArrayVar = new String[5];
strArrayVar[0] = "one";
strArrayVar[1] = "two";
strArrayVar[2] = "three";
strArrayVar[3] = "four";
strArrayVar[4] = "five";

The String Array is declared first in this case. The individual elements are then given values in the following line. After initializing the String Array, you can use it generally in your program.

String array’s length/size

You’re aware that arrays have a length property that can be used to determine the size of the array. It is also true for String Arrays. Further, an array’s size is determined by the size or length of the array (any array). As a result, you can use the following statement to find the array’s length named arrayVar.

int len = arrayVar.length;

// Let's write a program to display the length of a String Array.

public class Codeunderscored
{
    public static void main(String[] args) {

    //declare and initialize a string array     
    String[] numArrayVar = {"one","two", "three", "four", "five"};
    int len = numArrayVar.length;  //get the array length

    //showing the length
    System.out.println("Length of numArrayVar{\"one\",\"two\", \"three\", \"four\", \"five\"}:" + len);
    }
}

The length property comes in handy when you need to loop through a string array to process it or print it.

Iterating through a string array and printing It

We’ve gone over the declaration, initialization, and length properties of a String Array so far; now it’s time to go over each array element and print the String Array elements. You can traverse over a String Array using for loop and enhanced for loop, just like any other array. A Java method below shows how to traverse/iterate the array and output its elements using an improved for a loop.

public class Codeunderscored
{
    public static void main(String[] args) {
        //declaration and String Array initialization
        String[] numArrayVar = {"one","two", "three", "four", "five"};

        System.out.println("using for loop to show elements in the String Array:");

        // for loop for iterating over the given string array

        for(int i=0; i<numArrayVar.length;i++)
            System.out.print(numArrayVar[i] + " ");
     
        System.out.println("\n");
     
        System.out.println("using enhanced for loop to display elements in the String Array:");

        //iterating over the string array using  enhanced for loop

        for(String var:numArrayVar)
            System.out.print(var + " ");
    }
}

Both the usual for loop and advanced for loop are utilized to traverse the string array in the above application. It’s worth noting that there’s no need to declare a limit or an end condition in the case of an improved for a loop. When using the ‘ for ‘ loop, you must define the start and end conditions.

Add to the array of strings

Like other data structures, String Arrays can have elements added to them. This section looks at the various techniques for adding an element to the string array.

Using pre-allocation

Pre-allocation is a technique for allocating resources ahead of time. You generate an array with a bigger size using this method. For example, if you need to store 5 elements in an array, you’ll construct a 10-element array. The latter simply allows you to add new elements to the array’s end.

The following is an example of how to add a new element to the Pre-allocated Array.

import java.util.*;
public class Codeunderscored
{
    public static void main(String[] args) {
        String[] langArray = new String[7];
        // initial array values
        langArray[0] = "Python";
        langArray[1] = "Java";
        langArray[2] = "JavaScript";
        langArray[2] = "C++";
        System.out.println("The initial Array is:" + Arrays.toString(langArray));
        countOfItems = 4;
 
        // try adding new values to the array's end
        String newLang = "Go";
        colorsArray[countOfItems++] = newLang;
        System.out.println("Array after adding one element:" +  
                  Arrays.toString(langArray));
    }
}

It’s worth noting that the array’s empty space is set to Null. The disadvantage of this strategy is that it wastes space because you may have an extensive array that isn’t used.

Making use of a new array

This method creates a new array more extensive than the original array so that the new element may be accommodated. After generating the new array, all of the previous array’s items are transferred to it, and then the new element is appended to the end. The following is an example program that uses the new array to add an element.

importjava.util.*;
 
public class Codeunderscored
{
    public static void main(String[] args) {
        //original array
        String[] langArray = {"Python", "Java", "JavaScript", "C++" };    
        System.out.println("Original Array: " + Arrays.toString(langArray));
 
        //length of original array
        int initialLength = langArray.length;

        // Adding a new entry to the string array
        String newLang= "Go";

        // create a new array with a length that is greater than the previous array 
        String[] newArray = new String[ initialLength + 1 ];

        // all the elements of the original array should be copied to the new array
        for (int i=0; i <langArray .length; i++)
        {
            newArray[i] = langArray [i];
         }
        // near the end of the new array, add a new element
        newArray[newArray.length- 1] = newLang;

        // create a new Array that is identical to the original array and print it
        langArray = newArray;   
        System.out.println(" Displaying array items after adding a new item: " + Arrays.toString(langArray));
    }
}

Because the software must maintain two arrays, this technique results in memory and performance overhead.

ArrayList as a type of collection

ArrayList as an intermediary data structure can also be used to add an element to a String array. The following is an example.

import java.io.*;
import java.lang.*;
import java.util.*;
 
class Codeunderscored {
 
    public static void main(String[] args)
    {
          // initial array  definition
          String langArray[]
            = { "Java", "Python", "C++", "C#", "JavaScript", "Go" };
 
        // printing of the original array
        System.out.println("Initial Array:\n"
                           + Arrays.toString(langArray));
 
        // new element to be added
        String newLang = "Ruby";
 
        // convert the array to arrayList
        List<String>langList
            = new ArrayList<String>(
                  Arrays.asList(langArray));
 
        // Add the new element to the arrayList
        langList.add(newLang);
 
        // Convert the Arraylist back to array
        langArray = langList.toArray(numArray);
 
        // showing the array that has been the changed
        System.out.println("\nArray with value " + newLang
                           + " added:\n"
                           + Arrays.toString(langArray));
    }
}

The string array is first turned into an ArrayList using the asList method, as seen in the above application. The add method is then used to add the new element to the ArrayList. The ArrayList is transformed back to an array when the element is inserted. When compared to the previous approaches, this one is more efficient.

What a string array contains

The ‘contains’ method can determine whether or not a given string is present in the string array. Because this method belongs to the ArrayList, you must first convert the string array into an ArrayList. The ‘contains’ technique is demonstrated in the following example.

import java.io.*;
import java.lang.*;
import java.util.*;
 
class Codeunderscored {
 
     public static void main(String[] args)
    {         
         String[] programmingLanguages = new String[]{"C++", "Java", "Go", "C", "Python"};
 
        // Convert String Array to List
        List<String>languagesList = Arrays.asList(programmingLanguages);
        String languageToCheck = "Java";
        if(languagesList .contains(languageToCheck)){
           System.out.println("The Langugae " + languageToCheck + " is present in the string array");
        }
       else
       System.out.println("The Language " + languageToCheck + " is not present in string array" );
    }
}

We began by determining whether the given string array containing the string ‘Go.’ A relevant message is displayed since it is present. The String to be tested is then changed to ‘JavaScript.’ The ‘contains’ method returns false in this scenario.

It’s worth noting that the String supplied as a parameter to the contains function is always case-sensitive. If we pass ‘go’ as a parameter to the contains method in the above implementation, it will return false.

How do your sort a string array

‘Sorting in Arrays’ has already been covered in depth. The methods for sorting a string array are similar to those for sorting other arrays. The ‘sort’ method of the ‘Arrays’ class is implemented below, sorting the strings in the array in alphabetical order.

import java.util.*;
 
class Codeunderscored {
 
     public static void main(String[] args)
    {
        String[] programmingLanguages = {"Python","C++","C#","Python","JavaScript"};
        System.out.println("The initial array: "+Arrays.toString(programmingLanguages));
        Arrays.sort(programmingLanguages);
        System.out.println("Sorted array: "+Arrays.toString(programmingLanguages));
    }
}

The output of the preceding software includes both the original input array and an alphabetically sorted output array.

Looking for a string in the string array

You can also search for a particular string in a String Array by traversing each element of the String Array, in addition to the ‘contains’ technique we just mentioned. Each element of the String Array will be compared to the String to be searched.

When the first occurrence of the String is located, the search is finished. Then the appropriate index of the String in the array is returned. A relevant message is presented if the String is not found until the end of the string array. The following Java program demonstrates this implementation.

import java.util.*;

class Codeunderscored {
    public static void main(String[] args)
    {
      String[] compCompanies = { "Google", "DELL", "HP", "IBM", "Air BnB" };
        boolean found = false;
        int index = 0;
        String searchStr = "DELL";
       for (int i = 0; i <compCompanies .length; i++) {
       if(searchStr.equals(compCompanies[i])) {
            index = i; found = true;
            break;
            }
        }
       if(found)
          System.out.println( searchStr +" is available at the index "+index);
        else
          System.out.println( searchStr +" is not present in the array");
 
    }
}

When the string ‘DELL’ is found in a given string array, the above program returns the index corresponding to it.

String array to string conversion

Let’s look at how to create a string from a string array. We’ll go over three alternative ways to implement it, each with an example.

The toString method in action

The first method uses the ‘Arrays’ class’s toString function. It accepts a string array as a parameter and returns the array’s string representation. The toString method is demonstrated in the Java application below.

import java.util.*;
public class Codeunderscored {
    public static void main(String args[])
    {
        // string declaration
        String[] strArray = {"Coding","is","my","favorite","hobby"};
 
        System.out.println("The String array converted to string:" + Arrays.toString(strArray));
    }
}

The ‘toString’ method is used in the above software to display the string representation of the specified string array.

The StringBuilder.Append() method

The ‘StringBuilder’ class is the next option for turning a string array into a string. Create a StringBuilder object and use the StringBuilder’s ‘Append’ function to append the string array members to the StringBuilder object. After appending all of the array members to the StringBuilder object, you can use the ‘toString’ method to acquire the string representation.

import java.util.*;
public class Codeunderscored {
    public static void main(String args[])
    {
        //string array
       String[] strArray = {"Coding","is","my","favorite","hobby"};
       System.out.print("The initial string array is:");
        //print string array
        for(String val:strArray)
              System.out.print(val + " ");
 
        System.out.println("\n");

        //using a string array to create a stringbuilder object
        StringBuilder stringBuilder = new StringBuilder();
         int i;
        for (i= 0; i <strArray.length; i++) {
             stringBuilder.append(strArray[i]+ " ");
        }
        //print the String
        System.out.println("obtaining the string from string array:" + stringBuilder.toString());
    }
}

The preceding software uses the StringBuilder class to convert a string array to a string.

Employing the Join Operation

You can also utilize the String class’s ‘join’ function to convert a string array to a string representation. The ‘join’ action requires two arguments: the first is the String’s separator or delimiter, and the second is the string array. In addition, the String is then separated by the separator supplied by the join procedure (first argument).

The program below shows how to utilize the join operation to get a string from a String Array.

import java.util.*;
public class Codeunderscored {
     public static void main(String args[])
    {
        //string array
        String[] strArray = {"Coding","is","my","favorite","hobby"};
        System.out.println("The initial string array is:");  
     
        // string array printing
        for(String val:strArray)
           System.out.print(val + " ");

        System.out.println("\n");
        //form a string from string array using join operation
        String combinedString = String.join(" ", strArray);
        //print the string
        System.out.println(" The String that is obtained from string array:" + combinedString);
    }
}

Conversion of a string to an equivalent array of strings

Let’s look at converting a string to a string array in reverse. This conversion can be done in two ways.

Utilizing the Split Operation

The split operation of the String class is the initial method of transforming a string into a string array. A delimiter(comma, space, etc.) can be used to separate a string and return the freshly created string array. The split operation is demonstrated in the following example.

public class Codeunderscored {
public static void main(String args[])
    {
        //declare a string
        String strVar = "This is unit code test prerequisites";
        // To split a string into a string array, use the split function.
        String[] strArray = strVar.split(" ", 6);
 
        System.out.println("The resultant String Array after splitting the string is \"" + strVar + "\":");
      
      //showing the string array
        int i;
        for (i=0;i<strArray.length;i++)
             System.out.println("strArray[" + i+ "]=" + strArray[i]);
    }
}

The above program splits the String based on space and returns a 5-element string array using the split function.

Using a regular expression pattern

Regular expressions is an approach for converting a string into a string array. You can define a pattern, and then the given String will be split according to the pattern. You can utilize the Java.util package’s Regex Pattern class. An example of applying patterns to convert a string to a String Array is shown below.

import java.util.Arrays;
import java.util.regex.Pattern;
 
public class Codeunderscored {
    public static void main(String args[])
    {
        // string declaration
        String strVar = "This is unit code test prerequisites";
        System.out.println("The initial string is:" + strVar + "\n");
        String[] strArray = null;
 
        //split string on space(" ")
        Pattern pattern = Pattern.compile(" ");

        //using the pattern split on string to get string array
        strArray = pattern.split( strVar );
 
        //printing the string array
        System.out.println("The resultant String Array after splitting the string using regex pattern:");
        for (int i=0;i<strArray .length;i++)
            System.out.println("strArray[" + i+ "]=" + strArray[i]);
    }
}

The pattern we have supplied in the above program is a space character. As a result, the String is divided into spaces, returning the string array. As you can see, regular expressions and patterns are a significantly more efficient programming approach.

Converting a string array to list

You can also make a list out of a string array. There are a couple of ways to do this that we’ve listed below.

Making use of custom code

The first way is to transform a string array into a list using bespoke code. A string array is browsed in this function, and each member is added to the list using the list’s add method. It is demonstrated in the following program.

import java.util.*;
 
public class Codeunderscored
{
    public static void main( String[] args )
    {
        //string array declaration
        String[] compCompanies = { "Google", "DELL", "HP", "IBM", "Air BnB" };

        System.out.println("The original string array:" + Arrays.toString(compCompanies));

        //definition of the arraylist with size same as string array
        List<String>strArrayList = new ArrayList<String>(numArray.length);
        //add string array elements to arraylist
        for (String str:compCompanies) {
           strArrayList.add(str );
        }
         System.out.println("\n The Arraylist that is created from string array:");
        //print the arraylist
        for (String str : strArrayList)
        {
             System.out.print(str + " " );
        }
    }
}

A list is produced first, as shown in the program above. The for-each loop is then used to add each entry of the string array to the list. The list is then printed.

Making use of collections.addAll() method

The second technique of turning a string array into a list is to use the Collections framework’s ‘addAll’ method. The addAll() method takes an ArrayList and a string array as input and transfers the string array’s contents to the ArrayList. The addAll method converts a string array to a list in the following software.

import java.util.*;
 
public class Codeunderscored
{
    public static void main( String[] args )
    {
        //a string array
        String[] compArray = { "DELL", "IBM", "Chromebook", "Lenovo", "Toshiba" };
        System.out.println("The original string array:" + Arrays.toString(vehiclesArray));

        //arraylist with size same as string array definition
        List<String> strArrayList = new ArrayList<String>(compArray .length);
 
        //add string array items to arraylist using Collections.addAll method
        Collections.addAll(strArrayList, compArray );
 
        System.out.println("\nArraylist  is created from string array:");
 
        // arraylist printing
        for (String str : strArrayList)
        {
             System.out.print(str + " " );
        }
    }
}

Using Collections, we turned a provided string array into a list in the previous software. addAll is a method that adds everything to a list.

Using the arrays.asList() method

Finally, the Array class has an ‘asList()’ method that directly converts a string array into a list. A Java program that uses asList is shown below.

import java.util.*;
 
public class Codeunderscored
{
     public static void main( String[] args )
    {
        //a string array
         String[] compArray = { "DELL", "IBM", "Chromebook", "Lenovo", "Toshiba" };
        System.out.println("The string array:" + Arrays.toString(compArray));
 
        //Conversion of Array to list using asList method
        List<String> strArrayList = Arrays.asList( compArray );
 
        System.out.println("\nThe Arraylist created from string array:");
 
        // arraylist printing
        for (String str : strArrayList)
        {
             System.out.print(str + " " );
        }
    }
}

The asList function of the Arrays class converts an array to a list and returns it, as seen above.

How to convert a list to a string array

We saw a few methods to convert a string array to a list in the previous section. Let’s look at the techniques for converting a list to a string array.

Using the ArrayList.get method()

The first method is the ArrayList get method, which returns the list’s elements. You can traverse the ArrayList and use the get method to retrieve an element, which can then be allocated to an array location. It is demonstrated in the following program.

import java.util.*;
 
public class Codeunderscored
{
    public static void main( String[] args )
    {
        //ArrayList initialization
         ArrayList<String> strArrayList= new ArrayList<String>();
        

	//adding new items to the arraylist
        strArrayList.add("maize");
        strArrayList.add("beans");
        strArrayList.add("potatoes");
        strArrayList.add("yams");
        strArrayList.add("sorghum");
         
        //ArrayList to Array Conversion
        String strArrayVar[] = new String[strArrayList .size()];              
        for(int j =0;j<strArrayList .size();j++){
         strArrayVar[j] = strArrayList.get(j);
         }
        //print array elements
        System.out.println("The String array is obtained from string arraylist:");
        for(String ary: strArrayVar){
        System.out.print(ary + " ");
        }
    }
}

The elements are first added to the ArrayList, and then the list is transformed into a string array using the ‘toArray’ method.

String array to integer array

You may need to do operations on numbers at some point. In this scenario, if your string array contains numeric data, it is recommended that you convert it to an int array. To do so, apply the ‘parseInt’ function to each array element and extract the integer. The program below explains how to convert a string array to an int array.

import java.util.*;
 
public class Codeunderscored
{
     public static void main( String[] args )
    {
       //string arrya declaration
       String [] strVar = {"30", "40","50", "60","70"};
      
     //printing of the string array
      System.out.println("The Original String Array:");
      for(String val:strVar)
         System.out.print(val + " ");
 
         System.out.println("\nThe integer array obtained from string array:");
        //declare an int array
        int [] intArray = new int [strVar .length];

        //assigning the string array values to int array
        for(int i=0; i<intArray .length; i++) {
           int_Array[i] = Integer.parseInt(str_Array[i]);
      }
      //display the int array
      System.out.println(Arrays.toString(int_Array));
    }
}

We have a string array in the above application that includes the numbers as strings. Each string array element is parsed using the ‘parseInt’ function and assigned to an int array in this program. This conversion will only work with a string array with numeric members. The compiler throws a ‘java.lang.NumberFormatException’ if any of the entries in the string array are non-numeric.

Conclusion

In Java, an array is a fundamental and widely used data structure. The array is a collection of comparable data type elements. In fact, it is one of the most commonly used data structures by programmers due to its efficiency and productivity. The items are stored in a single memory region.

An Array comprising a fixed number of String values is known as a String Array. On the other hand, a succession of characters is referred to as a String. A string is an immutable object, meaning its value cannot be modified. In addition, the String Array works in the same way as other Array data types.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *