Skip to content
Sharp

Core Java · interview question

If a cart contains prices {10, 20, 30}, what is the final value of 'total' after executing the following loop with an off-by-one error?

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

Correct answer

B. ArrayIndexOutOfBoundsException

Why

The loop tries to access an index equal to cart.length, which does not exist and causes an ArrayIndexOutOfBoundsException.

Test yourself on Core Java

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

Start free test
All Core Java questions →