MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / Average

Class Average

src/main/java/com/thealgorithms/maths/Average.java:15–80  ·  view source on GitHub ↗

A utility class for computing the average of numeric arrays. This class provides static methods to calculate the arithmetic mean of arrays of both double and int values. It also offers a Stream-based alternative for modern, declarative usage. All methods guard against {@code

Source from the content-addressed store, hash-verified

13 * <p>All methods guard against {@code null} or empty inputs.
14 */
15public final class Average {
16
17 // Prevent instantiation of this utility class
18 private Average() {
19 throw new UnsupportedOperationException("This is a utility class and cannot be instantiated.");
20 }
21
22 /**
23 * Computes the arithmetic mean of a {@code double} array.
24 *
25 * <p>The average is calculated as the sum of all elements divided
26 * by the number of elements: {@code avg = Σ(numbers[i]) / n}.
27 *
28 * @param numbers a non-null, non-empty array of {@code double} values
29 * @return the arithmetic mean of the given numbers
30 * @throws IllegalArgumentException if {@code numbers} is {@code null} or empty
31 */
32 public static double average(double[] numbers) {
33 if (numbers == null || numbers.length == 0) {
34 throw new IllegalArgumentException("Numbers array cannot be empty or null");
35 }
36 double sum = 0;
37 for (double number : numbers) {
38 sum += number;
39 }
40 return sum / numbers.length;
41 }
42
43 /**
44 * Computes the arithmetic mean of an {@code int} array.
45 *
46 * <p>The sum is accumulated in a {@code long} to prevent integer overflow
47 * when processing large arrays or large values.
48 *
49 * @param numbers a non-null, non-empty array of {@code int} values
50 * @return the arithmetic mean as a {@code long} (truncated toward zero)
51 * @throws IllegalArgumentException if {@code numbers} is {@code null} or empty
52 */
53 public static long average(int[] numbers) {
54 if (numbers == null || numbers.length == 0) {
55 throw new IllegalArgumentException("Numbers array cannot be empty or null");
56 }
57 long sum = 0;
58 for (int number : numbers) {
59 sum += number;
60 }
61 return sum / numbers.length;
62 }
63
64 /**
65 * Computes the arithmetic mean of a {@code double} array using Java Streams.
66 *
67 * <p>This method is a declarative alternative to {@link #average(double[])}.
68 * Instead of throwing on empty input, it returns an empty {@link OptionalDouble},
69 * following the convention of the Stream API.
70 *
71 * @param numbers an array of {@code double} values, may be {@code null} or empty
72 * @return an {@link OptionalDouble} with the mean, or empty if input is null/empty

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected