Bird
0
0

Consider this method:

hard📝 Application Q9 of 15
Java - Methods and Code Reusability
Consider this method:
public static int sumPositive(int[] numbers) {
  int sum = 0;
  for (int n : numbers) {
    if (n > 0) return sum + n;
  }
  return sum;
}

What is wrong with this method if the goal is to return the sum of all positive numbers?
AIt does not handle negative numbers
BIt returns after the first positive number, not the total sum
CIt returns sum before adding any number
DIt should return void
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the loop and return

    The method returns inside the loop on first positive number, stopping early.
  2. Step 2: Understand sum calculation goal

    To sum all positive numbers, return must happen after loop completes.
  3. Final Answer:

    It returns after the first positive number, not the total sum -> Option B
  4. Quick Check:

    Return inside loop stops summing early [OK]
Quick Trick: Return after loop to sum all values [OK]
Common Mistakes:
  • Returning inside loop too early
  • Ignoring negative numbers
  • Wrong return type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes