Your friend wrote the following function in Java.
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Your friend wrote the following function in Java. She says the function should return the average value of the given integer array a. Choose all of the correct statements about the function from the following:
static double mean(int[] a) {
int answer = 0;
for (int i = 0; i < a.length; i++) {
answer += a[i];
}
return answer / a.length;
}
Show answer & explanation
Statement B is correct: the function always returns a value (a double), but since answer / a.length performs integer division (both operands are int), decimals are truncated (not rounded). Statement A is wrong—if length is 0, a division-by-zero exception occurs (the function crashes rather than 'not returning'). Statement C is correct about overflow risk, but the question appears to ask for the single best answer. Statement B accurately captures the core behavior flaw.
Step-by-step Derivation:
Analysis of each statement:
A) FALSE: If a.length == 0, the line return answer / a.length; causes ArithmeticException: / by zero. The function throws an exception rather than silently 'not returning'.
B) TRUE: Assuming no overflow, the function always executes and returns a double value. However, answer / a.length is integer division (both operands are int), so the result is truncated (e.g., 7/2 = 3, not 3.5). The cast to double happens after division, not before, so fractional parts are lost.
C) TRUE: If array elements are large, their sum can exceed Integer.MAX_VALUE (2^31 - 1), causing integer overflow and wrapping to negative values. For example, summing [1000000000, 1000000000, 1000000000] overflows.
D) FALSE: Statements B and C are both correct.
If this is a 'select all that apply' question: B and C are both correct. If forced to choose one best answer, B is the primary flaw in the function's logic (truncation rather than proper averaging), while C is a potential runtime issue depending on input data.