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.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Information Technology MCQs
- Practice BCA MCQs
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Programming Books