Calculate Compound Interest in Java
Problem
Compound interest grows the principal by the same percentage every period, so the total after n years needs the growth factor raised to the power n, not just multiplied by n.
Given a principal amount, an annual interest rate, and a duration in years, calculate the compound interest earned.
Java Program
public class CalculateCompoundInterest {
public static void main(String[] args) {
double principal = 10000.0;
double rate = 5.0;
double time = 2.0;
double amount = principal * Math.pow(1 + rate / 100, time); // principal grows by the same % each year
double compoundInterest = amount - principal;
System.out.println("Compound Interest: " + compoundInterest);
}
}Output
Core Logic
Raising (1 + rate/100) to the power of time gives the total growth factor, and multiplying that by the principal gives the final amount — subtracting the principal back out leaves just the interest.
- 1
principalholds10000.0,rateholds5.0, andtimeholds2.0. - 2
Math.pow(1 + rate / 100, time)computes1.05raised to the power2, giving1.1025. - 3
principal * 1.1025gives the final amount,11025.0. - 4Subtracting the original
principalfrom that amount leaves just the interest,1025.0.
10000.0 at 5% for 2 years, the amount grows to 11025.0, so the interest is 1025.0.Key Point: The extra 25.0 compared to simple interest's 1000.0 comes from the second year earning interest on the first year's interest too — that's what 'compounding' means.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleBinaryOperator;
public class CalculateCompoundInterestLambda {
public static void main(String[] args) {
double principal = 10000.0;
double rate = 5.0;
double time = 2.0;
// The compounding formula is stored as a named, reusable lambda
DoubleBinaryOperator growthFactor = (r, t) -> Math.pow(1 + r / 100, t);
double amount = principal * growthFactor.applyAsDouble(rate, time);
double compoundInterest = amount - principal;
System.out.println("Compound Interest: " + compoundInterest);
}
}
Output
Core Logic
The growth-factor calculation can be pulled into a named lambda, separating 'how much things grow' from the surrounding amount and interest arithmetic.
- 1
DoubleBinaryOperator growthFactor = (r, t) -> Math.pow(1 + r / 100, t);stores the compounding formula as a lambda. - 2
growthFactor.applyAsDouble(rate, time)returns1.1025, the same value the inlineMath.pow(...)call would. - 3The rest of the calculation — multiplying by
principaland subtracting it back out — stays the same as the primary approach.
rate = 5.0 and time = 2.0, growthFactor.applyAsDouble(5.0, 2.0) returns 1.1025, leading to the same 1025.0 interest.Key Point: Naming the lambda growthFactor makes the formula's purpose explicit at the call site, which is easy to lose track of inside a longer inline expression like Math.pow(1 + rate / 100, time).