String Array in Java

An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types like primitive or non-primitive.

What is a String array in Java?

In Java,a String array is a fixed size objectthat stores string values. The String is a sequence of characters. It is an immutable object it means that values stored in the array object cannot be modified.

Declaring a String array in Java

There are the following ways to declare a String array in Java.

  1. Declaring without size


This way a String array myStrArraycan be declared like any other normal variable. But before using this, it should be instantiated with new.

  • Declaring with size


          Here, the String array myStrArray is declared using the newkeyword. It can store five elements.

Initializing a String array

There are two ways to initialize an array:

Inline Initialization: In inline initialization, first we declare an array after that put the elements of the array.


Here, myStrArray1 is declared and initialized immediately. And myStrArray2 is instantiated just after declaration.

We can also split the first statement, as follows:

Initialization after declaration


          Here, the strarr is first declared and then it is initialized one by one using the index.

Operations Performed on String array

  1. Size of String array

The Java String class provides a property called length. It determines the length of the string.


In the above class StringSize, a String array myStrArr1 is declared and initialized immediately. Length property is used to print the length of myStrArr1.

  • Iterating in an array


In the above program we have used Java for loop that iterates over the array. The loop starts from the 0 and execute till the length of the array.

  • Searching an element in a String array


In the above program, we have searched for the element b. In the if statement we have compared the element (b) with each element of the array. If match is not found, the break keyword breaks the execution of the loop and the execution jumps to the next statement.

  • Sorting a String array


String Array in Java

In the above code, Arrays.sort(myStrArr) method is used to sort the String array.

  • Converting a String array to a String


String Array in Java

     In the above code, the String array is converted into String using Arrays.toString(myStrArr) method.

  • Converting a String array to a List and adding a new element to the List


String Array in Java

          In the above code, Arrays.asList(myStrArr) method is used to convert the String array myStrArr to a List.

In this way, we have understood String arrays in Java and various operations performed on them.

Pin It on Pinterest

Share This