Write a Java Program to Calculate Standard Deviation

Calculating the standard deviation of a set of numbers is an important statistical task.

Standard deviation is a measure of how much the individual data points deviate from the mean value.

It is a widely used measure of dispersion or spread of data.

In this tutorial, we will explore how to write a Java program to calculate the standard deviation.


Before diving into the program, let’s first understand the mathematical formula for standard deviation.

The formula for calculating the standard deviation is as follows:

Standard Deviation = sqrt((sum of (x – mean)^2) / n)

Where x is the individual data point, mean is the average value of the data points, and n is the total number of data points.

Now that we understand the formula let’s write the Java program to calculate the standard deviation:

import java.util.Scanner;
import java.lang.Math;

public class StandardDeviation {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of elements in the array: ");
        int n = input.nextInt();
        double[] arr = new double[n];
        double sum = 0.0, mean, standardDeviation = 0.0;

        System.out.print("Enter " + n + " elements: ");
        for (int i = 0; i < n; i++) {
            arr[i] = input.nextDouble();
            sum += arr[i];
        }

        mean = sum / n;

        for (int i = 0; i < n; i++) {
            standardDeviation += Math.pow(arr[i] - mean, 2);
        }

        standardDeviation = Math.sqrt(standardDeviation / n);

        System.out.println("The standard deviation of the given numbers is: " + standardDeviation);
    }
}

In the above program, we have used a Scanner object to take user input for the number of elements in the array and the values of those elements.

We have then used a for loop to calculate the sum of the elements and the mean value of the array.

We have then used another for loop to calculate the standard deviation using the formula mentioned above.

Finally, we have printed the calculated standard deviation.


In conclusion, calculating the standard deviation of a set of numbers is a useful statistical measure.

With the help of the Java program above, we can easily calculate the standard deviation of a set of numbers.