Java array length – How to get array size in Java by using length method

What is Java array length method?

Java array class comes up with the length() method by which you can get the size of an array. The length method returns int number which is the total elements in the given array.

See an example of array length

This is quite useful, for example, getting the total size that can be used in displaying array items with for loop.

How to use the length method of array

The syntax of using the length method is:


Where Arrname is the name of the array for what you want to get array size.

An example of getting the size of array

In this example, an array of three elements is created for demonstration purpose. After declaring and assigning the values, the length method is used for getting the size of that array.

The returned value after using the array length method is assigned to an int type variable. Finally, the size of the array is displayed:

Java array length

You can see, the array length is displayed as 3. The output of the above example will be:

The array length is: 3

Example of using length method of array with for loop

The example below uses the length method of the array to get total array elements and then it is used in for loop to display all items of arrays.

Java array-length for loop

See graphic of above example

The output will be:

New York



As you can see, the strState.length returned the length of given array that is used to loop through the strState array.

Also see: Java array | Java String array

Was this article helpful?

Related Articles

Leave A Comment?