banner



Java How To Create A String Array

This tutorial on Java String Array Explains how to Declare, Initialize & Create String Arrays in Java and Conversions that we can Carry out on String Array:

Arrays are an important data structure in Java that are used to store different types of data from primitive to the user-defined. We have already seen the basics of Arrays and the other major operations that can be performed on Arrays.

In one of our previous tutorials, we have discussed the various types of data that an Array can hold.

=> A-Z Of Java Training For Beginners

Java String Array & Various Methods

One of the data types that arrays can hold is a string. In this case, the array is called a String array.

What You Will Learn:

  • What Is A String Array In Java?
    • Declaring A String Array
    • Initializing A String Array
    • Length/Size Of A String Array
    • Iterating And Printing A String Array
    • Add To The String Array
      • Using Pre-allocation
      • Using A New Array
      • Using ArrayList
      • String Array Contains
    • Sort A String Array
    • Search For A String In The String Array
    • Convert String Array To String
      • Using The toString Method
      • Using StringBuilder.Append() Method
      • Using Join Operation
    • Convert String To The String Array
      • Using Split Operation
      • Using Regex Pattern
    • Convert String Array To List
      • Using Custom Code
      • Using Collections.addAll () Method
      • Using Arrays.asList ()
    • Convert List To The String Array
      • Using ArraList.get()
      • Using ArrayList.toArray() Method
    • Convert String Array To Int Array
    • Frequently Asked Questions
  • Conclusion
    • Recommended Reading

What Is A String Array In Java?

We can have an array with strings as its elements. Thus, we can define a String Array as an array holding a fixed number of strings or string values. String array is one structure that is most commonly used in Java. If you remember, even the argument of the 'main' function in Java is a String Array.

String array is an array of objects. This is because each element is a String and you know that in Java, String is an object. You can do all the operations on String array like sorting, adding an element, joining, splitting, searching, etc.

In this tutorial, we will discuss the string array in Java in detail along with the various operations and conversions that we can carry out on string arrays.

Declaring A String Array

A String Array can be declared in two ways i.e. with a size or without specifying the size.

Given below are the two ways of declaring a String Array.

String[] myarray ;   //String array declaration without size
String[] myarray = new String[5];//String array declaration with size

In the first declaration, a String Array is declared just like a normal variable without any size. Note that before using this array, you will have to instantiate it with new.

In the second declaration, a String Array is declared and instantiated using new. Here, a String array 'myarray' with five elements is declared. If you directly print the elements of this array, you will see all the null values as the array is not initialized.

Let's implement a program that shows a String Array declaration.

public class Main { 	public static void main(String[] args) { 		 		String[] myarray;		//declaration of string array without size 		String[] strArray = new String[5];  //declaration with size  		//System.out.println(myarray[0]);   //variable myarray might not have been initialized 		//display elements of second array 		System.out.print(strArray[0] + " " +strArray[1]+ " " + strArray[2]+ " " + 		strArray[3]+ " " +strArray[4]); 	} }        

Output:

Declaring a string array - output

The above program shows two ways of declaring a String Array. As mentioned earlier, the first declaration is without size and instantiation. Hence before using this array, you should instantiate it using new. In the above program, the array myarray is used without instantiation and thus it results in compiler error (commented statement).

The second declaration is with the size. So when individual elements of this String array are printed, the values of all the elements are null as the array was not initialized.

Initializing A String Array

Once the String Array is declared, you should initialize it with some values. Otherwise, the default values that are assigned to String elements are null. Thus, after the declaration, we proceed to initialize the array.

A String array can be initialized either inline along with the declaration or it can be initialized after declaring it.

First, let's see how a String array can be initialized inline.

String[] numarray = {"one", "two", "three"}; String[] strArray = new String[] {"one", "two", "three", "four"};        

In the above String Array, the initializations are inline initializations. The String Array is initialized at the same time as it is declared.

You can also initialize the String Array as follows:

String[] strArray = new String[3]; strArray[0] = "one"; strArray[1] = "two"; strArray[2] = "three";        

Here the String Array is declared first. Then in the next line, the individual elements are assigned values. Once the String Array is initialized, you can use it in your program normally.

Length/Size Of A String Array

You know that to get the size of the array, arrays have a property named 'length'. This is true for String Arrays as well.

The size or length of the array (any array) gives the number of elements present in the array. Thus, in order to get the length of the array named myarray, you can give the following expression.

int len = myarray.length;

Let's implement a program that will output the Length of a String Array.

public class Main { 	public static void main(String[] args) { 	//declare and initialize a string array		 	String[] numArray = {"one","two", "three", "four", "five"}; 	int len = numArray.length;	//get the length of array 	//display the length 	System.out.println("Length of numArray{\"one\",\"two\", \"three\", \"four\", \"five\"}:" + len); 	} }        

Output:

Size of a string array - Output

The length property is useful when you need to iterate through string array to process it or simply print it.

Iterating And Printing A String Array

So far, we have discussed declaration, initialization and length property of a String Array, and now it's time for us to traverse through each element of the array and also print the String Array elements.

As with all arrays, you can iterate over a String Array using for loop and enhanced for loop.

Given below is a Java implementation that demonstrates the usage of an enhanced for loop to traverse/iterate the array and print its elements.

public class Main { 	public static void main(String[] args) { 		//declare and initialize a string array 		String[] numArray = {"one","two", "three", "four", "five"}; 		System.out.println("String Array elements displayed using for loop:"); 		// for loop to iterate over the string array 		for(int i=0; i<numArray.length;i++) 			System.out.print(numArray[i] + " "); 	 		System.out.println("\n"); 	 		System.out.println("String Array elements displayed using enhanced for loop:"); 		//enhanced for loop to iterate over the string array 		for(String val:numArray) 			System.out.print(val + " "); 	} }        

Output:

Iterating and Printing a string array - output

In the above program, both for loop and enhanced for loop are used for traversing the string array. Note that in the case of enhanced for loop, it is not required to specify the limit or end condition. In the case of the 'for' loop, you need to specify the start and end condition.

Add To The String Array

Just like the other data types, you can add elements for String Arrays as well. In this section, let's see the various methods to add an element to the string array.

Using Pre-allocation

In this method, you create an array having a larger size. For Example, if you have to store 5 elements in the array, then you will create an array with size 10. This way you can easily add new elements at the end of the array.

An example that implements the addition of an element to the Pre-allocated array is shown below.

import java.util.*; public class Main { 	public static void main(String[] args) { 		String[] colorsArray = new String[5]; 		// initial array values 		colorsArray[0] = "Red"; 		colorsArray[1] = "Green"; 		colorsArray[2] = "Blue"; 		System.out.println("Original Array:" + Arrays.toString(colorsArray)); 		intnumberOfItems = 3;  		// try to add new value at the end of the array 		String newItem = "Yellow"; 		colorsArray[numberOfItems++] = newItem; 		System.out.println("Array after adding one element:" + 	                   Arrays.toString(colorsArray)); 	} }        

Output:

Using pre-allocation - ouput

Note that the unoccupied space in the array is set to Null. The disadvantage of this method is that there is a wastage of space as you might create a big array that may remain unoccupied.

Using A New Array

In this method, you create a new array having a size that is greater than the original array so that you can accommodate the new element. After creating the new array, all the elements of the original array are copied to this array and then the new element is added to the end of the array.

An example program to add an element using the new array is shown below.

importjava.util.*;  public class Main { 	public static void main(String[] args) { 		//original array 		String[] colorsArray = {"Red", "Green", "Blue" };     		System.out.println("Original Array: " + Arrays.toString(colorsArray));  		//length of original array 		int orig_length = colorsArray.length; 		//new element to be added to string array 		String newElement = "Orange"; 		//define new array with length more than the original array 		String[] newArray = new String[ orig_length + 1 ]; 		//add all elements of original array to new array 		for (int i=0; i <colorsArray.length; i++) 		{ 			newArray[i] = colorsArray [i]; 		 } 		//add new element to the end of new array 		newArray[newArray.length- 1] = newElement; 		//make new array as original array and print it 		colorsArray = newArray;    		System.out.println("Array after adding new item: " + Arrays.toString(colorsArray)); 	} }        

Output:

Using a new array - output

This approach clearly results in memory and performance overhead as you have to maintain two arrays in the program.

Using ArrayList

You can also add an element to String array by using ArrayList as an intermediate data structure.

An example is shown below.

import java.io.*;  import java.lang.*;  import java.util.*;   class Main {       public static void main(String[] args)      {            // define initial array            String numArray[]             = { "one", "two", "three", "four", "five", "six" };           // print the original array          System.out.println("Initial Array:\n"                            + Arrays.toString(numArray));           // new element to be added          String newElement = "seven";           // convert the array to arrayList         List<String>numList             = new ArrayList<String>(                   Arrays.asList(numArray));           // Add the new element to the arrayList         numList.add(newElement);           // Convert the Arraylist back to array          numArray = numList.toArray(numArray);           // print the changed array         System.out.println("\nArray with value " + newElement                            + " added:\n"                            + Arrays.toString(numArray));      }  }        

Output:

Using ArrayList - output

As shown in the above program, the string array is first converted into an ArrayList using the asList method. Then the new element is added to the ArrayList using the add method. Once the element is added, the ArrayList is converted back to the array.

This is a more efficient approach when compared to the ones discussed previously.

String Array Contains

In case you want to know if a certain string is present in the string array or not, then you can use the 'contains' method. For this, you need to first convert the string array into ArrayList as this method belongs to the ArrayList.

The following implementation shows the use of the 'contains' method.

import java.io.*;  import java.lang.*;  import java.util.*;   class Main {        public static void main(String[] args)      {                   String[] words = new String[]{"C++", "Java", "C", "Python"};          // Convert String Array to List         List<String>wordslist = Arrays.asList(words);         String tochk = "Java";         if(wordslist.contains(tochk)){            System.out.println("The word " + tochk + " present in string array");         }        else        System.out.println("The word " + tochk + " not present in string array" );     } }        

Output:

String array contains - output

First, we checked if the given string array contains the string 'Java'. As it is present, an appropriate message is displayed. Next, we change the string to be checked to 'C#'. In this case, the 'contains' method returns false.

String to be checked to 'C#' - output

Note that, for the contains method, the string passed as an argument are always case-sensitive. Thus in the above implementation, if we provide 'java' as an argument to contains method, then it will return false.

Sort A String Array

We have already seen a detailed topic on 'Sorting in Arrays'. The methods to sort a string array are the same just like the other arrays.

Given below is an implementation of the 'sort' method of 'Arrays' class that sorts the strings in the array in alphabetical order.

import java.util.*;   class Main {        public static void main(String[] args)      {          String[] colors = {"red","green","blue","white","orange"};         System.out.println("Original array: "+Arrays.toString(colors));         Arrays.sort(colors);         System.out.println("Sorted array: "+Arrays.toString(colors));     } }

Output:

Sort a string array - output

The output of the above program shows the original input array as well as the output array that is sorted alphabetically.

Search For A String In The String Array

Apart from the 'contains' method we just discussed, you can also search for a particular string in a String Array by traversing each element of the String Array. Here, you will compare each element in the String Array with the string to be searched.

The search is terminated when the first occurrence of the string is found and the corresponding index of the string in the array is returned. If the string is not found till the end of the string array, then an appropriate message is displayed.

This implementation is shown in the following Java program.

import java.util.*;  class Main {      public static void main(String[] args)      {        String[] strArray = { "Book", "Pencil", "Eraser", "Color", "Pen" };         boolean found = false;         int index = 0;         String searchStr = "Pen";        for (int i = 0; i <strArray.length; i++) {        if(searchStr.equals(strArray[i])) {             index = i; found = true;              break;             }         }        if(found)           System.out.println(searchStr +" found at the index "+index);         else           System.out.println(searchStr +" not found in the array");      } }        

Output:

Search for a string in the string array - output

The above program searches for the string 'Pen' in a given string array and returns its corresponding index when it is found.

Convert String Array To String

Let's discuss the ways to convert string array to string. We will discuss three different methods to do this with an example of each.

Using The toString Method

The first method is using the 'toString' method of the 'Arrays' class. It takes the string array as an argument and returns the string representation of the array.

The following Java program shows the usage of the toString method.

import java.util.*; public class Main {      public static void main(String args[])      {          //declare a string         String[] str_Array = {"This","is","Software","Testing","Help"};           System.out.println("String array converted to string:" + Arrays.toString(str_Array));     }  }        

Output:

Using the toString method

The above program uses the 'toString' method to display the string representation of the given string array.

Using StringBuilder.Append() Method

The next approach of converting string array to string is by using the 'StringBuilder' class. You should create an object of type StringBuilder and use the 'Append' method of StringBuilder to append the string array elements to the StringBuilder object one by one.

Once all the array elements are appended to the StringBuilder object, you can use the 'toString' method on this object to finally get the string representation.

import java.util.*; public class Main {      public static void main(String args[])      {          //string array        String[] str_Array = {"This","is","Software","Testing","Help"};         System.out.print("Original string array:");         //print string array         for(String val:str_Array)               System.out.print(val + " ");          System.out.println("\n");         //construct a stringbuilder object from given string array         StringBuilder stringBuilder = new StringBuilder();         for (int i = 0; i <str_Array.length; i++) {              stringBuilder.append(str_Array[i]+ " ");         }         //print the string         System.out.println("String obtained from string array:" + stringBuilder.toString());     }  }        

Output:

Using StringBuilder.Append() method - output

The above program shows the conversion of string array to string using the StringBuilder class.

Using Join Operation

You can also use the 'join' operation of the String class to change the string array into a string representation.

The 'join' operation takes two arguments, first is the separator or delimiter for the string and the second argument is the string array. The join operation then returns the string separated by a specified separator (first argument).

Check the following program that demonstrates the use of join operation to obtain a string from a String Array.

import java.util.*; public class Main {       public static void main(String args[])      {          //string array         String[] str_Array = {"This","is","Software","Testing","Help"};          System.out.println("Original string array:");                //print the string array                for(String val:str_Array)            System.out.print(val + " ");         System.out.println("\n");         //form a string from string array using join operation         String joinedString = String.join(" ", str_Array);         //print the string         System.out.println("String obtained from string array:" + joinedString);     }  }        

Output:

Using join operation - output

Convert String To The String Array

Let's see the reverse operation of converting a string to a string array. There are two methods to do this conversion.

Using Split Operation

The first method of converting a string to string array is to use the split operation of the String class. You can split the string on a specified delimiter (comma, space, etc.) and return the newly generated string array.

The following implementation demonstrates the usage of split operation.

public class Main {  public static void main(String args[])      {          //declare a string         String myStr = "This is Software Testing Help";          //use split function to split the string into a string array         String[] str_Array = myStr.split(" ", 5);           System.out.println("String Array after splitting the string \"" + myStr + "\":");         //display the string array         for (int i=0;i<str_Array.length;i++)               System.out.println("str_Array[" + i+ "]=" + str_Array[i]);      }  }        

Output:

Using split operation - output

The above program uses the split function to split the string based on space and returns a 5 element string array.

Using Regex Pattern

The next method to convert the string into a string array is by using regular expressions. You can specify a pattern and then split the given string according to the specified pattern.

You can use Regex Pattern class belonging to java.util package.

Given below is an example of using patterns to convert string to String Array.

import java.util.Arrays; import java.util.regex.Pattern;  public class Main {      public static void main(String args[])      {          //declare a string         String myStr = "This is Java series tutorial";         System.out.println("The original string:" + myStr + "\n");         String[] str_Array = null;          //split string on space(" ")         Pattern pattern = Pattern.compile(" ");         //use pattern split on string to get string array         str_Array = pattern.split(myStr );          //print the string array         System.out.println("String Array after splitting the string using regex pattern:");         for (int i=0;i<str_Array.length;i++)              System.out.println("str_Array[" + i+ "]=" + str_Array[i]);      }  }

Output:

Using regex pattern - output

In the above program, the pattern that we have specified is a space character. Thus, the string is split into spaces and returns the string array. As you can already deduce, using regular expressions and patterns is a far more efficient way of programming.

Convert String Array To List

You can also convert string array to a list. We have listed a few methods to do this

Using Custom Code

The first method is to use custom code to convert string array to list. In this method, a string array is traversed and each element is added to the list using add method of the list.

The following program shows this implementation.

import java.util.*;  public class Main {     public static void main( String[] args )     {         //a string array         String[] numArray = { "One", "Two", "Three", "Four", "Five" };         System.out.println("The string array:" + Arrays.toString(numArray));         //define arraylist with size same as string array         List<String>str_ArrayList = new ArrayList<String>(numArray.length);         //add string array elements to arraylist         for (String str:numArray) {            str_ArrayList.add(str );         }          System.out.println("\nArraylist created from string array:");         //print the arraylist         for (String str : str_ArrayList)         {              System.out.print(str + " " );         }     } }        

Output:

Using custom code- output

As shown in the above program, a list is created first. Then using the for-each loop, each element of the string array is added to the list. Finally, the list is printed.

Using Collections.addAll () Method

The second method of converting string array to a list is by using the 'addAll' method of the Collections framework. The method addAll() takes the ArrayList and string array as input and copies the contents of the string array to ArrayList.

The following program shows the usage of the addAll method to convert string array to list.

import java.util.*;  public class Main {     public static void main( String[] args )     {         //a string array         String[] vehiclesArray = { "moped", "car", "SUV", "bicycle", "bus" };         System.out.println("The string array:" + Arrays.toString(vehiclesArray));         //define arraylist with size same as string array         List<String> str_ArrayList = new ArrayList<String>(vehiclesArray.length);          //add string array elements to arraylist using Collections.addAll method         Collections.addAll(str_ArrayList, vehiclesArray );          System.out.println("\nArraylist created from string array:");          //print the arraylist         for (String str : str_ArrayList)         {              System.out.print(str + " " );         }     } }        

Output:

Using Collections.addAll () method - output

In the above program, we have converted a given string array into a list using the Collections.addAll method.

Using Arrays.asList ()

Finally, the Array class provides the method 'asList()' that converts the given string array into the list directly.

Given below is a Java program that uses asList.

import java.util.*;  public class Main {      public static void main( String[] args )     {         //a string array         String[] vehiclesArray = { "moped", "car", "SUV", "bicycle", "bus" };         System.out.println("The string array:" + Arrays.toString(vehiclesArray));          //Convert array to list using asList method         List<String> str_ArrayList = Arrays.asList(vehiclesArray );          System.out.println("\nArraylist created from string array:");          //print the arraylist         for (String str : str_ArrayList)         {              System.out.print(str + " " );         }     } }        

Output:

Using Arrays.asList ()

As shown above, the asList method of Arrays class converts the array to list and returns this list.

Convert List To The String Array

In the previous section, we saw a few methods to convert string array to list. Now, let's see the methods to convert the list to a string array.

Using ArraList.get()

The first method is the get a method of ArrayList that returns the individual elements of the list. You can traverse the ArrayList and call get method that will return an element that can then be assigned to the array location.

The following program shows this implementation.

import java.util.*;  public class Main {     public static void main( String[] args )     { 	    //ArrayList initialization 	     ArrayList<String> str_ArrayList= new ArrayList<String>(); 	    //add items to the arraylist 	    str_ArrayList.add("str1"); 	    str_ArrayList.add("str2"); 	    str_ArrayList.add("str3"); 	    str_ArrayList.add("str4"); 	    str_ArrayList.add("str5"); 		 	    //ArrayList to Array Conversion  	    String str_Array[] = new String[str_ArrayList.size()];               	    for(int j =0;j<str_ArrayList.size();j++){ 		str_Array[j] = str_ArrayList.get(j); 	     } 	    //print array elements 	    System.out.println("String array obtained from string arraylist:"); 	    for(String ary: str_Array){ 		System.out.print(ary + " "); 	    }     } }        

Output:

Using ArraList.get() - output

The above program shows the conversion of ArrayList to string array using get method.

Using ArrayList.toArray() Method

ArrayList provides a method 'toArray ()' that returns an array representation of ArrayList. Thus, you can obtain a string array from a string ArrayList using this method.

Check the following program that uses the toArray method.

import java.util.*;  public class Main {     public static void main( String[] args )     { 	    //ArrayList initialization 	     ArrayList<String> str_ArrayList= new ArrayList<String>(); 	    //add items to the arraylist 	    str_ArrayList.add("Mumbai"); 	    str_ArrayList.add("Delhi"); 	    str_ArrayList.add("Pune"); 	    str_ArrayList.add("Chennai"); 	    str_ArrayList.add("Kolkata"); 		 	    //ArrayList to Array Conversion using toArray method 	    String str_Array[]=str_ArrayList.toArray(new String[str_ArrayList.size()]); 	    //print array elements 	    System.out.println("String array obtained from string arraylist:"); 	    for(String ary: str_Array){ 		System.out.print(ary + " "); 	    }     } }        

Output:

Using ArrayList.toArray() method - Output

First, the elements are added to the ArrayList and then using the 'toArray' method, the list is converted to a string array.

Convert String Array To Int Array

Sometimes you may need to do operations on numbers. In this case, if your string array has numeric contents, then it is advisable to convert this string array to int array. For this, you need to use the function 'parseInt' on each array element and extract the integer.

The following program shows the conversion of string array into an int array.

import java.util.*;  public class Main {      public static void main( String[] args )     {        //string arrya declaration        String [] str_Array = {"10", "20","30", "40","50"};       //print the string array       System.out.println("Original String Array:");       for(String val:str_Array)          System.out.print(val + " ");           System.out.println("\nThe integer array obtained from string array:");         //declare an int array         int [] int_Array = new int [str_Array.length];         //assign string array values to int array         for(int i=0; i<str_Array.length; i++) {            int_Array[i] = Integer.parseInt(str_Array[i]);       }       //display the int array       System.out.println(Arrays.toString(int_Array));     } }        

Output:

Convert string array to int array - output

In the above program, we have a string array that contains the numbers as strings. In this program, each of the string array elements is parsed using the 'parseInt' function and assigned to an array of type int.

Note that this conversion will work only on a string array having numeric elements. If any of the elements in the string array is non-numeric, then the compiler throws 'java.lang.NumberFormatException'.

Frequently Asked Questions

Q #1) What is the difference between an Array and a String in Java?

Answer: The array is a contiguous sequence of elements. The string is a sequence of characters terminated by a null character. Strings are immutable i.e. once defined they cannot be changed. Any changes were done to string results in a new string.

Arrays are mutable. Arrays can contain elements of various data types including strings.

Q #2) How do you declare an array in Java?

Answer: The general way to declare an array in java is:

type array_name[];
Or
type[] array_name;

Hence if myarray is an array variable with int type elements then this array can be declared as:

int myarray[];
Or
int[] myarray;

Q #3) How do I create an Array of Strings?

Answer: If strArray is a string array, then its declaration can be:

String[] strArray;
Or
String strArray[];

Q #4) What is String [] args?

Answer: String[] args in Java is an array of strings that contain command-line arguments that can be passed to a Java program.

Q #5) Can Arrays hold strings?

Answer: Yes. Just like arrays can hold other data types like char, int, float, arrays can also hold strings. In this case, the array becomes an array of 'array of characters' as the string can be viewed as a sequence or array of characters.

Conclusion

In this tutorial, we have seen the details of the String Array in Java. We went through all the major concepts related to String Array including declaration, definition, and initialization of string array in Java.

We have also discussed several operations like searching, sorting, join, etc. and conversion of string array into the list, string, int array, etc. With this, we complete our discussion on string arrays.

In our subsequent tutorials, we will discuss multi-dimensional arrays in Java.

=> Learn Java From Scratch Here

Java How To Create A String Array

Source: https://www.softwaretestinghelp.com/java-string-array/

Posted by: proctorgoicerouth.blogspot.com

0 Response to "Java How To Create A String Array"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel