Skip to content

Java String Array Length

Java String array length example shows how to get string array length using the length property of the Java array.

How to get string array length in Java?

Arrays in Java are objects. Objects in Java have certain properties and methods. The length is such a property of an array. It stores the total number of items in the array object.

To get string array length, we need to use the same length property. The length is not a method, but it is a property of the String array. For accessing a property of an object, we do not need to specify the brackets after its name. So we need to specify array.length and not array.length().

Below given code example shows how to get the length of a string array.

Output

Please also make sure that the array reference is not null. If it is, accessing the length property of it will throw NullPointerException exception as shown below.

Output

Once we get the string array length, we can use it to iterate through all elements of it using the for loop. The array index starts from 0, so we are going to start the loop with 0 and will go up to array length – 1 index using the for loop as shown below.

Output

We can also use the string array length to check if the array is empty or not. We can do that by comparing the length with the 0 as given below.

Output

If you like to learn more about the string in Java, please visit the Java String 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.