Java Array: Find Mean

By: Stephen Patrick | 25 May 2016 | Category: Java Array

Related Contents

Java Array: Find Mean

Here we will show an example of how to find the mean of a java integer array.

Java Array: Find Mean Example

The mean of an array is simply the average value of its sum. We sum up all the values of the array and divide it by the length of the java array.

If the java array has a length of 0 then the mean of the java array will be equal to 0. Lets write some code to sum the java array.

   public static long sumIntArray(int[] arrayToSum) {
       if(arrayToSum ==null || arrayToSum.length <=0) {
           return 0;

       long result = 0;
       for (int i = 0;  i < arrayToSum.length; i++) {
           result += arrayToSum[i];

       return result;

    public static long findMeanOfIntArray(int[] arrInt) {
        if (arrInt == null || arrInt.length <= 0) {
            return 0;

        return sumIntArray(arrInt) / arrInt.length;

Java Array Mean Code Explanation

In the above code we define two static methods the first will sum the array, adding the value of each element in the java integer array.

To find the mean of the java array we created the method findMeanOfIntArray. This method calls the java method sumIntArray passing the java int array to sum. To find the mean which is the average of the java int array we divide the returned sum by the length of the java int array.

   System.out.println(String.format("The mean of the array %s is: %s", arrayToString(arrayToSum),

The result of the above code outputs: The mean of the array {1,2,3,4,5} is: 3