Java Array length Syntax
length is a public final field that every array has. It holds an int and is read without parentheses.
What is the difference between length, length() and size()?
Arrays have the length field. A String has the length() method, which returns the number of characters. Collections such as ArrayList have the size() method, which returns the number of elements they hold right now and grows as you add more.
Java Array Length Examples
The following are examples of getting the length of an array in Java. You can run any of these examples in the online Java code runner and change the arrays to see the length change.
Get the length of an array
length counts every element, including those that still hold the default value. An array created with new int[10] has a length of 10 before any value is assigned.
Loop through an array with length
Indexes start at 0, so the last element is at length - 1. Use i < length as the loop condition.
Get the length of a 2D array
A two-dimensional array is an array of arrays. matrix.length returns the number of rows, and matrix[0].length returns the number of elements in the first row. Rows can have different lengths.
Compare length, length() and size()
The example stores the same word as a char array, as a String and as an element of a List.