Java – Array Length
To get the length of an array in Java, use the length field on the array. It returns an int representing the number of elements in that array.
For example, if an array contains six elements, array.length is 6. Java array indexes start at 0, so the last valid index is array.length - 1.
Unlike a String, an array does not use a length() method. Unlike an ArrayList or other collection, an array does not use size(). Arrays use the field length without parentheses.
Java Array Length Syntax
The syntax for reading the number of elements in an array is:
int length = array.length;
The length field is available on every Java array, including arrays of primitive values, arrays of objects, and multidimensional arrays. The Java Language Specification defines it as a public final field, so the length of an array cannot be changed after that array is created. See the Java Language Specification, Chapter 10: Arrays.
Example 1 – Get Array Length using array.length
In the following example, we initialized an integer array nums with six elements. Then we used the length field as nums.length to get the number of elements in the array.
ArrayLength.java
/**
* Java Example Program to get Array Length
*/
public class ArrayLength {
public static void main(String[] args) {
//an array
int[] nums = {25, 86, 41, 97, 22, 34};
//get length of array
int len = nums.length;
System.out.println(len);
}
}
Run the program from a terminal or an IDE. The array contains six values, so nums.length returns 6.
Output
6
Array Length and Valid Java Array Indexes
Array length is the number of elements, not the last index. Because Java arrays are zero-indexed, an array of length 6 has valid indexes from 0 through 5.
int[] nums = {25, 86, 41, 97, 22, 34};
System.out.println(nums.length);
System.out.println(nums[0]);
System.out.println(nums[nums.length - 1]);
Output
6
25
34
Trying to access nums[nums.length] is outside the valid index range and results in an ArrayIndexOutOfBoundsException.
Use array.length in a Java for Loop
A common use of array.length is as the loop boundary when iterating through an array by index. The condition i < nums.length stops the loop before i reaches an invalid index.
int[] nums = {25, 86, 41, 97, 22, 34};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
If you only need each element and do not need its index, an enhanced for loop is often simpler. You still do not need to count elements manually when the array’s length field is available.
Example 2 – Get Array Length – Using For Loop
Another way to determine the number of elements is to traverse the array with a for loop and increment a counter for each element. This is unnecessary when array.length is available, but it demonstrates how the count corresponds to the number of elements visited.
ArrayLength2.java
/**
* Java Example Program to get Array Length
*/
public class ArrayLength2 {
public static void main(String[] args) {
//an array
int[] nums = {25, 86, 41, 97, 22, 34};
//get length of array
int len=0;
for(int num:nums) len++;
System.out.println(len);
}
}
Run the program.
Output
6
The output is again 6, matching the value returned directly by nums.length in the previous example.
This example counts one element on each iteration, so it reaches the same result. In normal Java code, prefer nums.length when you need the array length because it gives the value directly.
Java Array Length for an Empty Array
An array may contain zero elements. In that case, its length is 0.
int[] numbers = new int[0];
System.out.println(numbers.length);
Output
0
This makes array.length == 0 a direct way to check whether an existing array is empty.
Java Array Length Is Fixed After Array Creation
The length of an array is fixed when the array object is created. For example, new int[4] always creates an integer array with four element positions. You can replace the values stored in those positions, but you cannot resize that same array object.
int[] numbers = new int[4];
System.out.println(numbers.length);
numbers = new int[7];
System.out.println(numbers.length);
Output
4
7
The second assignment does not resize the first array. It creates a different array of length 7 and makes numbers refer to it. If you need a collection that grows or shrinks as elements are added or removed, an ArrayList is usually more suitable.
Length of a Two-Dimensional Array in Java
A two-dimensional Java array is an array whose elements are themselves arrays. Therefore, matrix.length gives the number of row arrays, while matrix[row].length gives the length of a specific row.
int[][] matrix = {
{10, 20, 30},
{40, 50, 60}
};
System.out.println(matrix.length);
System.out.println(matrix[0].length);
System.out.println(matrix[1].length);
Output
2
3
3
Java also supports jagged arrays, where different rows can have different lengths. In that case, check the length of each row separately instead of assuming that every row has the same number of elements.
int[][] values = {
{1, 2},
{3, 4, 5, 6}
};
System.out.println(values.length);
System.out.println(values[0].length);
System.out.println(values[1].length);
Output
2
2
4
Java Array length vs String length() vs Collection size()
Java uses different APIs for arrays, strings, and collections. The following distinction prevents a common compile-time mistake.
| Value type | How to get the count | Example |
|---|---|---|
| Array | length field | numbers.length |
| String | length() method | text.length() |
| ArrayList / List | size() method | list.size() |
For an array, numbers.length() and numbers.size() are not valid. Use numbers.length.
What Happens When the Java Array Reference Is null?
The length field belongs to an array object. If the array reference is null, there is no array object from which to read the length, so evaluating array.length throws a NullPointerException.
int[] numbers = null;
if (numbers != null) {
System.out.println(numbers.length);
}
Check for null first when a variable is allowed to contain either an array reference or null.
Get Java Array Length with java.lang.reflect.Array
Most programs should use array.length. Reflection-based code is different: when an array is held as an Object and its component type is only known at runtime, java.lang.reflect.Array.getLength() can read its length. The method is documented in the Java SE API for java.lang.reflect.Array.
import java.lang.reflect.Array;
public class ReflectArrayLength {
public static void main(String[] args) {
Object values = new int[]{10, 20, 30, 40};
int length = Array.getLength(values);
System.out.println(length);
}
}
Output
4
The reflection method is intended for code that works with array objects generically. For a normally typed array variable such as int[] or String[], array.length is clearer.
Java Array Length: Key Points
- Use
array.lengthto get the number of elements in a Java array. lengthis a field, not a method, so do not writearray.length().- An array of length
nhas valid indexes from0ton - 1. - An empty array has a length of
0. - An array’s length is fixed after that array object is created.
- For a two-dimensional array, use
array.lengthfor the outer array andarray[row].lengthfor a row. - Use
String.length()for strings andList.size()for lists.
In this Java Tutorial, we learned how to get the length of an array with array.length, use the length safely with indexes and loops, and work with empty and multidimensional arrays.
TutorialKart.com