| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice Test
Share
easy Solved by 6 students
Java Enhanced For Loop Summation
< Prev
Next >

How would the method analyzeThis behave when called on an instance of NumberAnalyzer containing an array initialized with {2, 5, 8, 11}?
Consider the following class definition and the attempt to compute the sum of even integers within an array using an enhanced for-loop.

public class NumberAnalyzer {
  private int[] nums;

  public int analyzeThis() {
    int sum = 0;
    for (int num : nums) {
      if (num % 2 == 0) {
        sum += num;
      }
    }
    return sum;
  }
}

How would the method analyzeThis behave when called on an instance of NumberAnalyzer containing an array initialized with {2, 5, 8, 11}?

A

The loop increments the sum by the array values that are divisible by 2: sum accumulates to 10.

B

The loop includes all numbers, even and odd, making the sum 26.

C

The loop exits prematurely and returns a sum of 2 given an array index out of bounds at the first non-even number.

D

The method returns a runtime error since the array includes values that are not integers.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1lsj0803092211 0m 00s 100
#2hitrishabhatia12 0m 00s 90
#3suhanakochhar00611 1m 26s 14
#4y.seong202723 3m 50s -40
#5gtsak3111 3m 33s -113
APFIVE © 2020.
Email: [email protected]|Privacy Policy