Q6 /20 Your friend wrote the following function in Java.
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Q6 /20
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
The function uses integer division (answer / a.length), which truncates decimals rather than rounding them. The return type is double, but the division is performed on two int values before implicit conversion to double. Statement A is incorrect because a.length of 0 would throw an ArithmeticException (not "no return"), and Statement C is misleading—overflow occurs in the answer accumulation, not because the array "is long" (length attribute).
Step-by-step Derivation:
Analyze each statement:
A) If a.length == 0: The expression answer / a.length causes ArithmeticException (division by zero), so the function throws an exception rather than "not returning a value." FALSE.
B) The function performs integer division: int / int = int, then implicitly converts to double. Decimals are truncated (0.9 becomes 0, -0.9 becomes 0), not rounded. The division always completes and returns a value (barring division by zero). TRUE.
C) Integer overflow can occur when summing large array elements into answer (int), but the phrasing "when a is long" is ambiguous/misleading—it refers to array length, not overflow likelihood. Technically overflow is possible, but the statement's framing is imprecise. The core issue is truncation, not overflow.
D) Incorrect because B is correct.
Correct answer: B