What is Java string array?
In this tutorial, we will show you how to create, initialize and print the string arrays in Java.
The string arrays are used to store the string elements in arrays.
>> See an example of the String array
Suppose, we want to store 50 States in our Java program in the string variables. What we can do is to create 50 string variables and store the State names in each variable as shown below:
StrState1 = “New York”
StrState2 = “Washington”
StrState3 = “Florida”
and so on.
On the other hand, if you make that variable [state] a string array, you can store all 50 state names in that single array. We will use the same State example to create, initialize and display a string array in the following section.
An example of String array Java
The String array is declared by using the String class which is followed by the array name.
In this example, we will create an array of the String elements where we will store the US State names. After that, we will use a for loop to display array elements.
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class array_ex {
public static void main(String []args) {
String strState[] = new String[3]; //declaring array of three items
strState[0] =“New York”;
strState[1] =“Texas”;
strState[2] =“Florida”;
//Printing array
for (int i=0;i<strState.length;i++){
System.out.println(strState[i]);
}
}
}
|
The output will be:
New York
Texas
Florida
Alternatively, you can declare and assign values to the Java String array as follows:
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class array_ex {
public static void main(String []args) {
String strState[] = {“New York”,“Texas”,“Florida”}; //declaring and assign values
//Printing array
for (int i=0;i<strState.length;i++){
System.out.println(strState[i]);
}
}
}
|
The output will be:
New York
Texas
Florida
In the above examples, you can see, a string array is declared while the values can be given at the time of declaration or you can use the index numbers to assign the values to array elements later.
You may also like to read: Java array | Java array length
Leave A Comment?