Average Value of an Array in Java - Quiz

Total: 5 questions

1. 

How do I find the average of an array in Java in one line?

Use the Stream API: Arrays.stream(nums).average().orElse(0). The average() method works for int[], long[], and double[] arrays and returns an OptionalDouble, while orElse(0) supplies a default value for an empty array.

2. 

Why does the array {1, 2, 3, 4} give 2 instead of 2.5 when computing the average?

Because both the sum and the array length are of type int, and dividing two int values in Java is integer division: the fractional part is discarded. To get the exact result, cast one of the operands to double: (double) sum / nums.length.

3. 

What does the average() method return for an empty array, and how does that differ from a loop-based solution?

An empty OptionalDouble, because the average of zero elements is undefined. You provide a default value with orElse(). A loop-based solution over an empty double[] array would quietly compute 0.0 / 0 and return NaN.

4. 

Is there a built-in average() method in the Math or Arrays class?

No. Neither java.lang.Math nor java.util.Arrays has such a method. The standard way is Arrays.stream(nums).average(), i.e. the average() method of the primitive streams IntStream, LongStream, and DoubleStream.

5. 

How do you avoid overflow when summing a large int[] array to compute its average?

The sum of many large int values can exceed the int range, silently producing an incorrect result with no error at all. It is safer to accumulate the sum in a long variable, or to use the Stream API: for an IntStream, the average() method accumulates the sum in a long.

Page 1 of 1