Core Java · interview question
Given the following code snippet, how can it be optimized to avoid unnecessary iterations when calculating total discounts? for (int i = 0; i < discounts.length; i++) { if (discounts[i] == 0) continue; totalDiscount += discounts[i]; }?
Multiple choiceHardchapter-1-curatedpremiumcore-javaloops-and-iteration
int[] filteredDiscounts = Arrays.stream(discounts).filter(d -> d != 0).toArray(); for (int discount : filteredDiscounts) { totalDiscount += discount; }Answer and explanation
Correct answer
D. Filter the array before the loop
Why
Filtering the array before entering the loop reduces unnecessary iterations by excluding elements that won't contribute to the total. This optimizes performance by processing only the relevant data.
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?