Java ProgramsBasics & I/OCalculate Percentage

Calculate Percentage in Java

beginner·  Basics & I/O  ·  Arithmetic

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.

Input
obtained = 450.0, total = 500.0
Output
Percentage: 90.0

Java Program

Java
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

Percentage: 90.0

Core Logic

Dividing the obtained value by the total and multiplying by 100 gives the percentage directly, in a single expression.

How It Works
  1. 1obtained holds 450.0 and total holds 500.0.
  2. 2(obtained / total) * 100 evaluates to 90.0.
  3. 3The result is stored in percentage and printed with a label.
For 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

doublearithmetic expression

Approach 2: Java 8

Java
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

Percentage: 90.0

Core Logic

The percentage formula can be wrapped in a named lambda, turning 'compute a percentage' into a small reusable function.

How It Works
  1. 1DoubleBinaryOperator percentageOf = (part, whole) -> (part / whole) * 100; stores the formula as a lambda.
  2. 2percentageOf.applyAsDouble(obtained, total) calls it, returning the same result the inline expression would.
  3. 3The result is printed exactly as before.
With 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.

Key Concepts

DoubleBinaryOperatorfunctional interfacelambda expression

Related Programs