Variance of an Array in Java

The variance of an array indicates the degree to which the numbers of the array vary from its mean value.  Variance tells how values are spread out. Get an array of Integers arr[] with size n and calculate the variance of arr[].The Output should be printed in two decimal places.


Input 1:


5 6 7 8

Output 1:



(Variance is average of squared difference between the numbers and mean value)

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution


import java.util.*;

class Variance 


public static void main(String args[])


//Variable and  Object Declarations

        Scanner input = new Scanner(;

int n;

float sum = 0f;

float mean, variance;

//Getting size of Array & Declare Array arr[]

n = input.nextInt();

int arr[] = new int[n];

//Get n values to array arr[]

for(int i = 0; i<n; i++)


arr[i] = input.nextInt();


//Calcualte Sum and Mean

for(int i = 0; i<n; i++)


sum+= arr[i];


mean = sum/n;

//Calculate Variance for Whole Population


for(int i = 0; i<n; i++)


double diff = arr[i]-mean;

sum += Math.pow(diff,2);


variance = sum/(n);

System.out.printf("%.2f", variance);



Program Explanation


Related Programs