Java Program to Find the Number of Elements in an Array

This is a Java Program to Find the Number of Elements in an Array.

An array consisting of any number of elements is given. Now we take a variable and each time we encounter the next element of array it gets incremented. Hence we get the variable value as length of array. Also we can use inbuilt method length to find array length.

Here is the source code of the Java Program to Find the Number of Elements in an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. public class Length
  2. {
  3.     public static void main(String[] args) 
  4.     {
  5.         int a[] = {1,2,3,4,5};
  6.         int count = 0, i = 0, n;
  7.         try
  8.         {
  9.             while(a[i] != 'a')
  10.             {
  11.                 count++;
  12.                 i++;
  13.             }
  14.         }
  15.         catch(Exception e)
  16.         {
  17.             System.out.println("Number of elements in array:"+count);
  18.         }
  19.         n = a.length;
  20.         System.out.println("Number of elements(Using inbuilt method named length):"+n);
  21.     }
  22. }

Output:

$ javac Length.java
$ java Length
Number of elements in array:5
Number of elements(Using inbuilt method named length):5

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.