Skip to content

Java String array example

Java String array example shows how to define and initialize Java String array. The example also shows how to add elements and access elements from String array using for loop.

How to define Java String array?

Java String array is a collection of a fixed number of Java String objects. You can define a String array in the below given two methods.

This will define a String array of size 3. That means we can add 3 String objects to an array using the index as given below.

If you have a String variable, you can also directly assign it to the array using its index like given below.

Important Note: Java array starts from index 0. Since we defined our array’s size as 3, the array will have three elements at 0, 1, and 2 indexes. Accessing index 3 will throw the ArrayIndexOutOfBoundsException as given below.

If you know the string objects the array is going to have at the time of array definition, you can directly assign them while defining the String array as given below.

In this case, you do not have to define the size of an array. If you do so, there will be a compilation error.

For more information, please visit How to initialize String array example.

Java String array length

If you want to know the length of a string array, you can use its length property.

This method returns Java String array length

Output

Iterate Java String array

There are various ways using which you can iterate the String array. You can use a while loop, do while loop, for loop, and enhanced for loop to iterate it.

Iterate String array using for loop

You can iterate the String array using for loop with the help of the array’s length as given below.

Output

Note that we started the variable “i” as 0 and continued our loop till i is less than array length because array elements start at 0 index and go up to array size – 1 index.

Iterate String array using enhanced for loop

You can also use enhanced for loop to iterate the String array.

Output

Here we do not have to specify the size of an array.

Some other examples of Java array

String array initialize example
String array remove duplicates example
Print array example
Sort String array example
Reverse array example
String array to List example

This example is a part of the Java Array tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.