Data Structure String Values: Array Is An Object That Holds A Fixed Number of
Data Structure String Values: Array Is An Object That Holds A Fixed Number of
You must be aware of Java Arrays, it is an object that contains elements of a similar data
type. Also, they are stored in a continuous memory location. Strings, on the other hand, is a
sequence of character. It is considered as immutable object i.e, the value cannot be
changed. java String array works in the same manner. String Array is used to store a fixed
number of Strings.
For implementation ensure you get Java Installed. A string array is declared by the
following methods:
Now let us move ahead and checkout how to initialize a string array,
1 //inline initialization
2 String[] stringArray1 = new String[] {"R","S","T"};
3 String[] stringArray2 = {"R","S","T"};
4 //initialization after declaration
5 String[] stringArray3 = new String[3];
6 stringArray3[0] = "R";
7 stringArray3[1] = "S";
8 stringArray3[2] = "T";
All three arrays specified above have the same values.
Since there are only 3 elements in stringArray3, and the index starts from 0, the last index is
3. We could also use the formula (array length – 1) to ascertain the value of the index. On
accessing an index greater than 2, an exception will be raised.
Example:
Initialization of a string array can be done along with the declaration by using the new
operator in the syntax:
The property length of a string array can be used to determine the number of elements in
the Array.
Output:
array
Iteration over a string array is done by using java for loop, or java for each loop.
Output:
We can also make use of the enhanced for loop provided by Java 5:
In case the user wants to search for a specific value in the string array, for loop is used.
B found at index 1
The keyword break is used to stop the loop as soon as the element is found.
To sort the elements in the string array, we can implement our own sorting algorithm, or
we can invoke the Arrays class sorting method.
Initial array: [o ,e , i, u, a]