Skip to content
Sharp

Core Java · interview question

Which part of the following code is responsible for avoiding an off-by-one error?

Multiple choiceMediumchapter-1-curatedpremiumcore-javaloops-and-iteration
java
int[] prices = {10, 20, 30}; int total = 0; for (int i = 0; i < prices.length; i++) { total += prices[i]; }
Choose one answer
Answer and explanation

Correct answer

B. I < prices.length

Why

The condition 'i < prices.length' ensures the loop stops before accessing an out-of-bounds index, preventing an off-by-one error.

Test yourself on Core Java

A free test with instant, explained results. No account needed.

Start free test
All Core Java questions →