OA. free
Free
Accenture Core Computer Science Core Computer Science Medium

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;
}
Choose one option.
Show answer & explanation
Answer: B. Aside from cases of integer overflow, the function always returns some value. However, the decimals of the returned value are rounded.

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:

  1. Statement A: If a.length == 0, the division answer / a.length becomes 0 / 0, which throws java.lang.ArithmeticException: / by zero. The function does throw an exception, so it doesn't simply "not return any value"—it crashes. FALSE.

  2. Statement B: The return type is double, so the function always completes and returns a double value. However, answer / a.length is integer division (both operands are int), which truncates decimals. Only after this truncation is the result implicitly converted to double. For example, 5 / 2 = 2 (integer), then converted to 2.0 (double), not 2.5. TRUE.

  3. 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").

  4. Statement D: Since B is correct, D is false.

Answer: B