Calculate Discount Amount in Java
Problem
The simplest discount model applies the same fixed percentage to every price — one multiplication and division, no thresholds involved.
Given a price and a flat discount percentage, calculate the discount amount.
Java Program
public class CalculateDiscountAmount {
public static void main(String[] args) {
double price = 1000.0;
double discountPercent = 10.0;
double discountAmount = (price * discountPercent) / 100; // flat percentage of price
System.out.println("Discount Amount: " + discountAmount);
}
}Output
Core Logic
Multiplying the price by the discount percentage and dividing by 100 gives the discount amount directly, in a single expression.
- 1
priceholds1000.0anddiscountPercentholds10.0. - 2
(price * discountPercent) / 100evaluates to100.0. - 3The result is stored in
discountAmountand printed with a label.
price = 1000.0 with a 10% discount, (1000.0 * 10.0) / 100 gives 100.0.Key Point: Real discount schemes often vary the percentage by how much is spent — for example, a bigger discount above a certain price threshold — which needs conditional logic rather than a single flat percentage like this one.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleBinaryOperator;
public class CalculateDiscountAmountLambda {
public static void main(String[] args) {
double price = 1000.0;
double discountPercent = 10.0;
// The discount formula is stored as a lambda, named for what it computes
DoubleBinaryOperator discountOf = (p, percent) -> (p * percent) / 100;
double discountAmount = discountOf.applyAsDouble(price, discountPercent);
System.out.println("Discount Amount: " + discountAmount);
}
}
Output
Core Logic
The discount formula can be wrapped in a named lambda, turning 'compute a discount' into a small reusable function.
- 1
DoubleBinaryOperator discountOf = (p, percent) -> (p * percent) / 100;stores the formula as a lambda. - 2
discountOf.applyAsDouble(price, discountPercent)calls it, returning the same result the inline expression would. - 3The result is printed exactly as before.
price = 1000.0 and discountPercent = 10.0, discountOf.applyAsDouble(1000.0, 10.0) returns 100.0.Key Point: This is the same 'percent of an amount' shape used by the Simple Interest and Percentage pages — the same reusable idea applies just as well to a discount.