Skip to content
Sharp

Core Java · interview question

In the following code, what will happen if 'cartItems' is an empty array? for(int i = 0; i < cartItems.length; i++) { total += cartItems[i].price; }?

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

Correct answer

D. The loop will not execute

Why

If 'cartItems' is empty, 'cartItems.length' is 0, and the loop condition 'i < cartItems.length' is false initially, so the loop does not execute.

Test yourself on Core Java

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

Start free test
All Core Java questions →