Java Program to Find the Number of Elements in an Array

Write a Java program to find the number of elements in an array with an example. For example, in Java, we can use the array length function to find and print the total number of elements.

package NumPrograms;

public class ArrayCountElements1 {
	
	public static void main(String[] args) {
		
		int[] arr = new int[] {10, 20, 30, 40, 50, 60};
		
		int count = arr.length;
		
		System.out.println("The Total Number of Elemenst in an Array = " + count);
	}
}
Java Program to Find the Number of Elements in an Array

This Java program finds the number of elements in an array using the for loop.

package NumPrograms;

public class Example2 {
	
	public static void main(String[] args) {
		
		int[] arr = new int[] {22, 99, 8, 17, 6, 11, 1, 15, 2, 5, 4};
		
		int count = 0;
		
		for(int i : arr)
		{
			count++;
		}
		
		System.out.println("The Total Number = " + count);
	}
}
The Total Number = 11

In this Java example, we used a while loop to iterate array items with conditions that check whether the element equals character x. 

package NumPrograms;

public class Example3 {
	
	public static void main(String[] args) {
		
		int[] arr = new int[] {1, 9, 11, 4, 7, 22, 9, 17, 8};
		
		int count = 0;
		int i = 0;
		try 
		{
			while(arr[i] != 'x')
			{
				count++;
				i++;
			}
		}
		catch(Exception e)
		{	
			System.out.println("The Total Number of Items = " + count);
		}
	}
}
The Total Number of Items = 9