String Arrays in Java help us solve many programming problems that involve the use of a contiguous data structure such as arrays.
A string array is nothing but an array containing strings as its elements. Basically, strings are objects in java and the string array is the array of immutable string objects. In order to create a string array, we can either assign it initial values or create the array with a specified size and the new operator. The following example shows how to create an array of strings.
String[] my_arr=new String[10]; // an array of 10 strings
String[] my_arr1={"ab", "cd", "ef", "gh"}; // an array created with initial values
Examples of String Arrays in Java
Also, note the use of foreach loop in the following example. The foreach loop has the following syntax.
for(data-type variable-name: array_name)
{
// statements
}
The foreach loop works as follows. It traverses the entire array by taking each element of the array at a time.
class StringArray {
public static void main(String[] args) {
String mystring="The string arrays in Java simplify our task of dealing with strings";
System.out.println("Original string: "+mystring);
int elements_count=0;
System.out.println("Converting string into array...");
String[] str_array=mystring.split(" ", 0);
for(String x:str_array)
{
System.out.println(x);
elements_count++;
}
System.out.println("Total number of words in the string: "+elements_count);
}
}
Output
So, we can apply the string methods available in Java to the elements of the array. Besides, we can use the array methods available. This greatly simplifies the coding and development to become faster.
Example of Using String and Array Methods
The following example creates a string object. Then, an array is created using the split() method that splits the string when a space is encountered. Therefore, the string array contains each word of the string as its elements. Further, for each loop converts the first letter of each element of the string array to uppercase by using the toUpperCase() and the substring() method. Next, the Arrays.sort() method sorts the elements of the array.
import java.util.*;
class StringArray {
public static void main(String[] args) {
String mystring="The string arrays in Java simplify our task of dealing with strings";
System.out.println("Original string: "+mystring);
String[] str_array=mystring.split(" ", 0);
// Capitalize each word in the string
for(String x:str_array)
{
x=x.substring(0,1).toUpperCase()+x.substring(1);
System.out.println(x);
}
System.out.println("\nSorted Array...");
//sorting the array
Arrays.sort(str_array);
for(String x:str_array)
{
System.out.println(x);
}
}
}
Output
Similarly, we can use string arrays in many other applications that require manipulating a collection of strings.