Java – Array Length

To get the length of an array in Java, use length property on the array. length property returns an integer representing the number of elements in the array.

In this tutorial, we will learn how to find the length of an array in Java, considering various scenarios, and where this length property can be used.

Example 1 – Get Array Length using array.length

In the following example, we initialized an integer array nums with six elements. Then we used length property on nums as nums.length to get the number of elements in the array programmatically. We just printed it to the console, but you may use it for any of your requirement.

ArrayLength.java

</>
Copy
/**
 * 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 console, terminal or any IDE of your favorite. You should see an output of 6 as shown below.

Output

6

Example 2 – Get Array Length – Using For Loop

This is yet another inefficient way of finding the length of an array, which is using a for loop. But, this program helps you find the notion of what length of an array is, and an another way of solving the problem of finding the number of elements in an array.

ArrayLength2.java

</>
Copy
/**
 * 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

And you should see no difference in the output as that of in the previous example.

Conclusion

In this Java Tutorial, we learned how to find the length of an array, in many different ways. Some of them are straight away and efficient, and some are inefficient but educative.