Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

Java Program to Calculate Average of Numbers Using Arrays

Posted on July 15, 2025July 15, 2025 By Admin No Comments on Java Program to Calculate Average of Numbers Using Arrays

Calculating the average of numbers is a basic yet essential operation in programming. In Java, arrays offer a convenient way to store and manipulate a collection of data. In this article, we will explore various ways to calculate the average of numbers using arrays in Java.

What is an Average?

The average (or arithmetic mean) is calculated by summing all the elements and dividing by the number of elements.

Formula:

average = (sum of elements) / (total number of elements)

Approach 1: Using a for Loop (Static Input)

This is the most basic and widely used approach.

// Java code to calculate the average of numbers

public class AverageCalculator {
    public static void main(String[] args) {
        
        // Static array
        int[] arr = {10, 20, 30, 40, 50};
        int sum = 0;

        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }

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

Output

Average of Numbers: 30.0

Explanation:

  • We define a static array of integers.
  • Use a for loop to calculate the sum.
  • Compute the average by dividing sum by array length.

Approach 2: Using a for-each Loop

The enhanced for loop makes the code more readable and concise.

// Java code to calculate the average of numbers

public class AverageCalculator {
    public static void main(String[] args) {
        int[] arr = {15, 25, 35, 45, 55};
        int sum = 0;

        for (int num : arr) {
            sum += num;
        }

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

Approach 3: Taking User Input Using Scanner

This is useful when the array size and elements are provided by the user at runtime.

// Java code to calculate the average of numbers

import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Number of Elements: ");
        int n = scanner.nextInt();
        int[] arr = new int[n];

        int sum = 0;
        for (int i = 0; i < n; i++) {
            System.out.print("Enter " + (i+1) + " Element: ");
            arr[i] = scanner.nextInt();
            sum += arr[i];
        }

        double average = (double) sum / n;
        System.out.println("Average of Numbers: " + average);
        scanner.close();
    }
}

Approach 4: Using Java Streams (Java 8+)

Java 8 introduced the Stream API, which provides a functional way of computing averages.

// Java code to calculate the average of numbers

import java.util.Arrays;

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

        double average = Arrays.stream(arr).average().orElse(Double.NaN); // Handles empty arrays

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

Note:

  • The average() method returns an OptionalDouble.
  • Use orElse(Double.NaN) to handle the case of an empty array.

Approach 5: Using a Method for Reusability

Encapsulating logic into a method makes the code modular and reusable.

// Java code to calculate the average of numbers

public class AverageCalculator {

    public static double calculateAverage(int[] array) {
        int sum = 0;
        for (int num : array) {
            sum += num;
        }
        return (double) sum / array.length;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        double avg = calculateAverage(arr);
        System.out.println("Average of Numbers: " + avg);
    }
}

Approach 6: Handling Edge Cases (Empty Arrays)

Always consider edge cases like:

  • Empty arrays
  • Arrays with one element
  • Arrays with negative numbers or floating-point numbers
public class AverageCalculator {

    public static double calculateAverage(int[] array) {
        if (array == null || array.length == 0) {
            System.out.println("Array is empty or null.");
            return 0;
        }

        int sum = 0;
        for (int num : array) {
            sum += num;
        }
        return (double) sum / array.length;
    }

    public static void main(String[] args) {
        int[] numbers = {};
        double avg = calculateAverage(numbers);
        System.out.println("Average = " + avg);
    }
}
Java, Programs Tags:Java-Array, Java-Programs

Post navigation

Previous Post: JavaScript Array isArray() Method
Next Post: Java Program to Find the Largest Element of an Array

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • July 2025
  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • Interview Experience
  • Java
  • JavaScript
  • Lodash
  • PHP
  • Programs
  • Python
  • Selenium
  • Software Testing
  • Web Technologies
  • Web Templates

Recent Posts

  • Selenium – A Web Application Testing Framework
  • Java Program to Check Whether a Given String is Palindrome or Not
  • Java Program to Find the Second Largest Element of an Array
  • Adobe Interview Experience | Senior QA Engineer | Automation Test for Noida Office [Latest 2025]
  • Java Program to Find the Largest Element of an Array

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme