Calculate Simple Interest in Java
Problem
Simple interest grows by the same fixed amount every year, unlike compound interest — it's just principal times rate times time, divided by 100.
Given a principal amount, an annual interest rate, and a duration in years, calculate the simple interest earned.
Java Program
public class CalculateSimpleInterest {
public static void main(String[] args) {
double principal = 10000.0;
double rate = 5.0;
double time = 2.0;
double simpleInterest = (principal * rate * time) / 100; // P * R * T / 100
System.out.println("Simple Interest: " + simpleInterest);
}
}Output
Core Logic
Multiplying the principal, rate, and time together and dividing by 100 gives the interest directly, in one expression.
- 1
principalholds10000.0,rateholds5.0, andtimeholds2.0. - 2
(principal * rate * time) / 100evaluates to1000.0. - 3The result is stored in
simpleInterestand printed with a label.
10000.0 at 5% for 2 years, (10000.0 * 5.0 * 2.0) / 100 gives 1000.0.Key Point: Simple interest is always the same amount every year — 500.0 in year one and 500.0 again in year two — which is exactly what makes it 'simple' compared to compound interest.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleBinaryOperator;
public class CalculateSimpleInterestLambda {
public static void main(String[] args) {
double principal = 10000.0;
double rate = 5.0;
double time = 2.0;
// A reusable "percent of amount" lambda, applied once per year via time
DoubleBinaryOperator percentOf = (amount, percent) -> amount * percent / 100;
double simpleInterest = percentOf.applyAsDouble(principal, rate) * time;
System.out.println("Simple Interest: " + simpleInterest);
}
}
Output
Core Logic
Splitting the formula into 'percent of principal' and 'times the duration' lets a single reusable lambda handle the percentage part.
- 1
DoubleBinaryOperator percentOf = (amount, percent) -> amount * percent / 100;stores the percentage logic as a lambda. - 2
percentOf.applyAsDouble(principal, rate)computes the interest for a single year. - 3Multiplying that one-year result by
timeextends it to the full duration, giving the same total the inline formula would.
principal = 10000.0 and rate = 5.0, percentOf.applyAsDouble(10000.0, 5.0) gives 500.0 per year, and 500.0 * 2.0 gives 1000.0 total.Key Point: percentOf is a genuinely reusable building block — the same lambda could compute a discount or a tax amount just as easily, since 'percent of an amount' is the same operation in every case.