Skip to content
Sharp

Core Java · interview question

How can a 'for loop' be used to calculate the total price of items only if they belong to a specific category?

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

Correct answer

D. Filter within the loop

Why

By incorporating an 'if' condition inside the 'for loop', you can filter items based on a specific category and only accumulate their prices if they match the desired criteria.

Test yourself on Core Java

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

Start free test
All Core Java questions →