1Z0-811 Java Basics and Syntax Practice Question
A junior developer wrote the following code to calculate the sum of an array:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 1; i <= numbers.length; i++) {sum += numbers[i];
}
System.out.println("Sum: " + sum);
The developer expects the output to be 15, but the program throws an exception. What is the root cause and the correct fix?
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
Change to: for (int i = 0; i < numbers.length; i++)
The loop starts at index 1 instead of 0, and goes up to index numbers.length (which is 5), but valid indices are 0-4. So accessing numbers[5] throws ArrayIndexOutOfBoundsException. The correct fix is to start at i=0 and continue while i < numbers.length, which is option B. Option A uses an enhanced for loop, which is also a valid fix but changes the loop style; however, the question asks for the root cause and correct fix, and option B directly corrects the indexing. Option C changes the step to 2 and starts at 1, still wrong. Option D uses i <= numbers.length, which still causes out-of-bounds.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Change to enhanced for loop: for (int num : numbers) sum += num;
Why it's wrong here
This would work but does not directly fix the original loop; the question asks for fix of the given loop.
- ✓
Change to: for (int i = 0; i < numbers.length; i++)
Why this is correct
Correct start and condition.
- ✗
Change to: for (int i = 1; i < numbers.length; i += 2)
Why it's wrong here
This skips elements and still starts at 1.
- ✗
Change to: for (int i = 0; i <= numbers.length; i++)
Why it's wrong here
Still out of bounds because <= includes length which is invalid index.
Go deeper
Related to this question
About these practice questions
Courseiva writes every 1Z0-811 question from scratch — 481 in total, each with an explanation and a wrong-answer breakdown. None are copied from real exams or dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This 1Z0-811 practice question is part of Courseiva's free Oracle certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the 1Z0-811 exam.