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
The function performs integer division (answer / a.length), which truncates decimals rather than rounding them. Statement B is correct because it accurately identifies both the behavior (always returns a value) and the limitation (integer division truncates decimals). Statement A is incorrect—when a.length is 0, a java.lang.ArithmeticException is thrown (division by zero). Statement C is incorrect—the array type is int[], not a "long" array, though integer overflow is still theoretically possible with the sum. Statement D is incorrect because B is correct.
Step-by-step Derivation:
Analysis of each statement:
Statement A (Incorrect): If a.length == 0, the return statement attempts answer / 0, which throws java.lang.ArithmeticException (division by zero). The function does throw an exception rather than return normally.
Statement B (Correct): The function always returns a double value (except when division by zero occurs). The critical flaw is the integer division: answer / a.length performs division on two int values, producing an int result before implicit conversion to double. For example, if the sum is 7 and length is 2, 7 / 2 = 3 (not 3.5), then converted to 3.0. Decimals are truncated, not rounded.
Statement C (Incorrect): The parameter is int[] a (an integer array), not a long array. While integer overflow in the summation is theoretically possible with very large elements or many elements, the statement incorrectly describes the array type.
Statement D (Incorrect): Since B is correct, this is false.
Correct answer: B