Grails Cookbook - A collection of tutorials and examples

String Array Length in Java

String Array is a commonly used data structure when programming in Java. Although we can generally use List for greater flexibility, but sometimes using String Array is more suitable for a given scenario. Arrays in general have the property of having fixed number of elements and the size can't be changed throughout the lifetime of the data structure. When given a String Array as parameter to our method, it is common that we wish to know the length of it. Below are some examples on how to get the length of a String Array in Java.

String Array Length Property

All arrays in Java have the attribute length. It contains the fixed size of the array. We can use this to get the size of the given Java Array. For example:
/**
 * A simple example that displays the length of a String Array in Java
 */
public class StringArrayLengthExampleInJava
{
    public static void main(String[] args) {
        String[] fruitStringArray = { "Apple", "Banana", "Mango", "Avocado"};
        int fruitStringArrayLength = fruitStringArray.length;
        System.out.format("The length of the fruit String array is " + fruitStringArrayLength );
    }
}

The output will be:

The length of the fruit String array is 4

Note that length is read only and we can not assign values to it. Hence this code will not compile. If you are using an IDE, it will show the code in red. This is because the field length is declared as final, hence a value can't be assigned to it.
String[] fruitStringArray = { "Apple", "Banana", "Mango", "Avocado"};
fruitStringArray.length = 5;

Pitfalls

As always, be reminded of NullPointerException. For example, this code will raise an exception during runtime:
String[] sample = null;
System.out.println( sample.length );
This is because the variable sample is null and we can't invoke any fields or methods from it. But of course, it is okay if the array is not null but the individual elements are actually null. We can still get the length from the String Array. For example, both code samples below will have the same output:
String[] fruitStringArray = new String[5];
int fruitStringArrayLength = fruitStringArray.length;
System.out.format("The length of the fruit String array is " + fruitStringArrayLength );
String[] fruitStringArray = {null, null, null, null, null};
int fruitStringArrayLength = fruitStringArray.length;
System.out.format("The length of the fruit String array is " + fruitStringArrayLength );
Both code will create a String Array with size 5, but the contents are all null. The expected output of the code will be:
The length of the fruit String array is 5