Calculate Average of Numbers in Java

To calculate the average of numbers in Java, add all the values and divide the sum by the number of values. For an array, the count is available through array.length. For an ArrayList, use size().

The basic formula is average = sum / count. Use a floating-point type such as double or float when the average can contain a decimal part.

</>
Copy
double average = sum / count;

This tutorial shows how to calculate the average of numbers in a Java array using a while loop and an enhanced for loop, how to calculate the average of values in an ArrayList, and how to read numbers from the user with Scanner.

Why Java Average Calculations Should Use double or float

If both operands of the division are integers, Java performs integer division and discards the fractional part. For example, 7 / 2 evaluates to 3, not 3.5. Make at least one operand a floating-point value when a decimal result is required.

</>
Copy
int sum = 7;
int count = 2;

double average = (double) sum / count;
System.out.println(average);

Output

3.5

Example 1 – Average of Numbers in Array

In this example, we shall use Java While Loop, to compute the average.

Algorithm to Calculate Array Average with a While Loop

We shall use the following algorithm to find the average of numbers.

  1. Start.
  2. Read array of numbers. Or initialize an array with number, of whom you would like to find average.
  3. Initialize sum = 0;
  4. Initialize i = 0;
  5. Check if i is less than number of elements in array. If not go to step 8.
  6. Add sum with number in array at index i, and store in the sum itself.
  7. Increment i. Go to step 5.
  8. Compute average = sum / number of elements in array.
  9. Stop.

Java Program

</>
Copy
/**
 * Java Program - Average of Numbers
 */

public class Average {

	public static void main(String[] args) {
		//numbers
		int[] nums = {1, 2, 3, 4, 5, 6};
		
		float sum = 0;
		
		//compute sum
		int i=0;
		while(i < nums.length) {
			sum += nums[i];
			i++;
		}
		
		//compute average
		float average = (sum / nums.length); 
		
		System.out.println("Average : "+average);
	}
}

Note: We are using float datatype for sum variable to save the precision after computing average. If you use int datatype for sum, when dividing it with number of elements, we lose the decimal part of the average.

Output

Average : 3.5

Example 2 – Average of Numbers in Array

In this example, we shall use Java Advanced For Loop, to compute the average.

Algorithm to Calculate Array Average with an Enhanced For Loop

We shall use the following algorithm to find the average of numbers.

  1. Start.
  2. Read array of numbers. Or initialize an array with numbers, of whom you would like to find average.
  3. Initialize sum = 0;
  4. For each number in the array, add the number to sum.
  5. Compute average = sum / number of elements in array.
  6. Stop.

Java Program

</>
Copy
/**
 * Java Program - Average of Numbers
 */

public class Average {

	public static void main(String[] args) {
		//numbers
		int[] nums = {1, 2, 3, 4, 5, 6};
		float sum = 0;
		
		//compute sum
		for(int num:nums)
			sum += num;
		
		//compute average
		float average = (sum / nums.length); 
		
		System.out.println("Average : "+average);
	}
}

Output

Average : 3.5

Example 3 – Average of Numbers in ArrayList

In this example, we shall use Java Advanced For Loop, to compute the average.

Algorithm to Calculate the Average of ArrayList Elements

We shall use the following algorithm to find the average of numbers.

  1. Start.
  2. Read array of numbers. Or initialize an ArrayList with numbers, of whom you would like to find average.
  3. Initialize sum = 0;
  4. For each number in the ArrayList, add the number to sum.
  5. Compute average = sum / number of elements in array.
  6. Stop.

Java Program

</>
Copy
import java.util.ArrayList;

/**
 * Java Program - Average of Numbers
 */

public class Average {

	public static void main(String[] args) {
		//numbers
		ArrayList<Integer> nums = new ArrayList<Integer>();
		nums.add(10);
		nums.add(13);
		
		float sum = 0;
		
		//compute sum
		for(int num:nums) {
			sum += num;
		}
		
		//compute average
		float average = (sum / nums.size()); 
		
		System.out.println("Average : "+average);
	}
}

Output

Average : 11.5

Calculate Average in Java Using Scanner Input

When the numbers are entered at runtime, read the count first, then read each number, add it to the running sum, and divide by the count. The following program uses double so that integer and decimal inputs are both handled naturally.

</>
Copy
import java.util.Scanner;

public class AverageFromInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("How many numbers? ");
        int count = scanner.nextInt();

        if (count <= 0) {
            System.out.println("Enter a count greater than zero.");
            scanner.close();
            return;
        }

        double sum = 0.0;

        for (int i = 0; i < count; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            sum += scanner.nextDouble();
        }

        double average = sum / count;
        System.out.println("Average : " + average);

        scanner.close();
    }
}

For example, if the user enters 4 numbers and supplies 10, 15, 20, and 25, the sum is 70 and the average is 17.5.

Find the Average of Two Numbers in Java

For exactly two numbers, add the two values and divide by 2.0. Using 2.0 makes the division floating-point division even when both numbers are integers.

</>
Copy
public class AverageOfTwo {
    public static void main(String[] args) {
        int a = 8;
        int b = 5;

        double average = (a + b) / 2.0;

        System.out.println("Average : " + average);
    }
}

Output

Average : 6.5

Calculate the Average of a double Array in Java

If the source values can already contain decimal parts, store them in a double[] and use a double sum. Before dividing, check that the array is not empty.

</>
Copy
public class AverageOfDoubles {
    public static void main(String[] args) {
        double[] numbers = {2.5, 4.0, 5.5, 8.0};

        if (numbers.length == 0) {
            System.out.println("Cannot calculate the average of an empty array.");
            return;
        }

        double sum = 0.0;

        for (double number : numbers) {
            sum += number;
        }

        double average = sum / numbers.length;
        System.out.println("Average : " + average);
    }
}

Output

Average : 5.0

Calculate an Array Average with Java Streams

For an int[], Java streams provide an average() operation. It returns an OptionalDouble because an empty array has no average. The program below uses orElse() to provide a fallback value.

</>
Copy
import java.util.Arrays;

public class AverageWithStream {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};

        double average = Arrays.stream(numbers)
                .average()
                .orElse(Double.NaN);

        System.out.println("Average : " + average);
    }
}

Output

Average : 25.0

Common Errors When Calculating an Average in Java

  • Integer division: sum / count loses the fractional part when both variables are integers. Cast one operand to double, or store the sum as a floating-point value.
  • Empty array or list: there is no arithmetic mean when the number of values is zero. Check length or size() before dividing.
  • Wrong divisor: divide by the number of values that contributed to the sum, not by the last array index.
  • Using a narrow numeric type: for general-purpose average calculations, double usually provides more precision than float.

Summary: Calculating an Average in Java

In this Java Tutorial, we learned how to find the average of numbers in an array or a ArrayList, using looping statements.

The same rule applies to arrays, lists, and user input: compute the sum, determine how many values were included, and divide the sum by that count using floating-point arithmetic when a decimal result is possible. Check for an empty collection or a zero count before performing the division.