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
for (int i = 0; i < items.length; i++) { if (items[i].category.equals("desiredCategory")) { total += items[i].price; } }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.
More Core Java questions
- In a console shopping cart application, why might you separate input handling from calculations?
- What happens if a subclass does not implement an abstract method from its superclass?
- Why would you choose to use a switch statement instead of multiple if-else statements for handling order status?
- Which part of the following code is responsible for avoiding an off-by-one error?
- Why can using overly complex methods in an e-commerce application become a problem in production code?
- How can a class implementing an interface with a default method call that method from within an overridden method?