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 double value (no exception thrown), but because answer / a.length performs integer division before converting to double, fractional parts are lost (truncated/rounded down, not rounded to nearest). Statement A is false—if a.length == 0, a java.lang.ArithmeticException is thrown (division by zero), so it does return an exception, not "no value." Statement C is false—overflow occurs during summation in the int answer accumulator, not specifically because the array is "long" (the array length isn't the issue; the sum magnitude is). Statement D is false because B is correct.
Step-by-step Derivation:
Step-by-step analysis:
Statement A: If
a.length == 0, the divisionanswer / a.lengthbecomes0 / 0, which throwsjava.lang.ArithmeticException: / by zero. The function does throw an exception, so it doesn't simply "not return any value"—it crashes. FALSE.Statement B: The return type is
double, so the function always completes and returns a double value. However,answer / a.lengthis integer division (both operands areint), which truncates decimals. Only after this truncation is the result implicitly converted to double. For example,5 / 2 = 2(integer), then converted to2.0(double), not2.5. TRUE.Statement C: Integer overflow occurs when the sum of array elements exceeds
Integer.MAX_VALUE(2,147,483,647). This happens during accumulation in the loop, regardless of array length. The statement conflates array length with magnitude of elements. FALSE (overstated—overflow risk is based on element magnitude, not array being "long").Statement D: Since B is correct, D is false.
Answer: B