Calculate Percentage in Java
Problem
A percentage expresses a part as a fraction of a whole, scaled up to a value out of 100.
Given marks obtained and total marks, calculate the percentage scored.
Java Program
public class CalculatePercentage {
public static void main(String[] args) {
double obtained = 450.0;
double total = 500.0;
double percentage = (obtained / total) * 100; // part-of-whole scaled to 100
System.out.println("Percentage: " + percentage);
}
}Output
Core Logic
Dividing the obtained value by the total and multiplying by 100 gives the percentage directly, in a single expression.
- 1
obtainedholds450.0andtotalholds500.0. - 2
(obtained / total) * 100evaluates to90.0. - 3The result is stored in
percentageand printed with a label.
obtained = 450.0 out of total = 500.0, (450.0 / 500.0) * 100 gives 90.0.Key Point: Both obtained and total are declared as double — if they were int, obtained / total would perform integer division and truncate to 0 before the multiplication ever ran.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleBinaryOperator;
public class CalculatePercentageLambda {
public static void main(String[] args) {
double obtained = 450.0;
double total = 500.0;
// The percentage formula is stored as a lambda, named for what it computes
DoubleBinaryOperator percentageOf = (part, whole) -> (part / whole) * 100;
double percentage = percentageOf.applyAsDouble(obtained, total);
System.out.println("Percentage: " + percentage);
}
}
Output
Core Logic
The percentage formula can be wrapped in a named lambda, turning 'compute a percentage' into a small reusable function.
- 1
DoubleBinaryOperator percentageOf = (part, whole) -> (part / whole) * 100;stores the formula as a lambda. - 2
percentageOf.applyAsDouble(obtained, total)calls it, returning the same result the inline expression would. - 3The result is printed exactly as before.
obtained = 450.0 and total = 500.0, percentageOf.applyAsDouble(450.0, 500.0) returns 90.0.Key Point: Once percentageOf exists as a lambda, the same logic works for any part-and-whole pair — marks out of total marks, votes out of total votes, or any other ratio expressed as a percentage.