by Dinesh Thakur Category: array

After you create an array, you can access its length i.e. number of elements it holds. You can refer to the length of an array using its length field (which is implicitly public and final).A length field is associated with each array that has been instantiated. Because length field is a public member so it can be directly accessed using the array name and a dot operator. Its syntax is

The length data field can be accessed using the dot operator. For example: To access the number of elements in an array named num, use the following syntax,
You can use the length field of an array to control a numerical for loop that iterates over the elements of an array.

for(int i=0; i<num.length; i++)
System.out.println("Element num[" + i + "] = " + num[i]);

Now let us consider the following Example to explain it.

class Average

      public static void main (String[] args)
         int [] num={10,20,30,40,50};
         int sum= 0;
         for(int i=0; i<num.length;i++)
                    sum += num[i];
                    double avg = (double)sum/num.length;
                    System.out.println("Average : " +avg);

Getting Length of an Array in Java

In this Example, we calculates the average of 5 numbers. The array containing 5 numbers can be referenced using num_array variable. Here, we use num.length to get the length of the array referenced by num.
To calculate the average, we first add all the numbers in the array and then divide by the total numbers of elements. The result is then displayed

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles