Java program to find average of numbers in an array

One of the common numerical needs in programs is to calculate the average of a list of numbers. This involves taking the sum of the numbers and then dividing the result with the count of numbers.The following example illustrates the algorithm of finding average of a list of numbers,

Numbers are 12, 45, 98, 33 and 54
Sum = 12 + 45 + 98 + 33 + 54 = 242
Count of Numbers = 5
Average = Sum/Count = 242/5 = 48.4

Following is a sample Java program to calculate the average of numbers using an array. In this example, we use the Java inline syntax to initialize an array of numbers. We have also provided a utility function if you want to read the numbers from command line. If you are using the utility function, invoke the program using the following command line,

java CalcAverage 12 45 98 33 54

 * Calculate average of a list of numbers using array
public class CalcAverage {
    public static void main(String[] args) {
        CalcAverage ca = new CalcAverage();
        int[] numbers = new int[]{12, 45, 98, 33, 54};
        // Uncomment following line for inputting numbers from command line
        //numbers = ca.getNumbersFromCommandLine(args);

    private void findAndPrintAverage(int[] numbers) {
        // Use float for fractional results
        float sum=0.0f;
        for(int i=0;i<numbers.length;i++){
            sum += numbers[i];
        System.out.println("Average is "+sum/numbers.length);
     * Return an integer array of strings passed to command line
     * @param commandLine array of strings from command line
     * @return integer array
    private int[] getNumbersFromCommandLine(String[] commandLine) {
        int[] result = new int[commandLine.length];
        for (int i =0;i<commandLine.length;i++){
            result[i] = Integer.parseInt(commandLine[i]);
        return result;

Do you have a question on the above article or do you have a programming problem that you are unable to solve? Please email us.

Comments are closed.