In this tutorial, you will learn how to find the number of elements present in an array.
Illustration:
Array: {1, 2, 3, 4, 5} Number of elements = count of the elements = 5
Example: Program to print number of elements in an array
In this example, we have two arrays. We are finding the count of the elements in both the arrays. The steps to count the number of elements is same in any type of array, you can simply use .length
property of the array to quickly find the size of the array.
public class JavaExample { public static void main(String[] args) { //Initializing an int array int [] numbers = new int [] {2, 4, 6, 8, 10, 12}; // We can use length property of array to find the count of elements System.out.println("Number of elements in the given int array: " + numbers.length); //Initializing a String array String [] names = new String [] {"Rick", "Luna", "Steve", "John"}; System.out.println("Number of elements in the given String array: " + names.length); } }
Output:
Number of elements in the given int array: 6 Number of elements in the given String array: 4
Leave a Reply