Skip to content
Sharp

Core Java · interview question

What is a potential problem with the following code snippet when calculating cart totals? int i = 0; while (i < cart.length) { total += cart[i].price; }?

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

Correct answer

B. Infinite loop

Why

The loop lacks an increment step for the 'i' variable, leading to an infinite loop because the loop condition never becomes false. Adding 'i++' inside the loop would resolve this issue.

Test yourself on Core Java

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

Start free test
All Core Java questions →