English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input Output (I/O)

Java Reader/Writer

Other Java topics

Java program to calculate average using array

Java Examples Comprehensive

In this program, you will learn to calculate the average of a given array in Java.

Example: Program to calculate average using an array

public class Average {
    public static void main(String[] args) {
        double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };
        double sum = 0.0;
        for (double num: numArray) {
           sum += num;
        }
        double average = sum / numArray.length;
        System.out.format("The average is: %.2f", average);
    }
}

When running the program, the output is:

The average is: 27.69

In the above program, numArray stores the floating-point values required for the average.

Then, to calculate average, we need to first calculate the sum of all elements in the array. This is done using Java's for-completed by each loop.

Finally, we calculate the average using the following formula:

average = total sum of numbers / Total number of array elements (numArray.length)

In this case, the total number of elements is given by numArray.length.

Finally, we use the format() function to print the average so that we can use "%.2f"

Java Examples Comprehensive