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.
public class Length
{
public static void main(String[] args)
{
int a[] = {1,2,3,4,5};
int count = 0, i = 0, n;
try
{
while(a[i] != 'a')
{
count++;
i++;
}
}
catch(Exception e)
{
System.out.println("Number of elements in array:"+count);
}
n = a.length;
System.out.println("Number of elements(Using inbuilt method named length):"+n);
}
}
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.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Java Internship
- Apply for Information Technology Internship
- Practice Information Technology MCQs
- Buy Programming Books
- Practice Programming MCQs