Skip to content
Sharp

Core Java · interview question

How can the following code snippet be optimized to avoid unnecessary calculations?

Multiple choiceHardchapter-1-curatedpremiumcore-javacode-reading-and-debugging
java
int price = 100;
int discount = (price > 50) ? 10 : 5;
int finalPrice = price - discount;
System.out.println(finalPrice);
Choose one answer
Answer and explanation

Correct answer

A. Use a ternary operator

Why

A ternary operator can replace the if-else statement, making the assignment of 'finalPrice' more concise and efficient.

Test yourself on Core Java

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

Start free test
All Core Java questions →