Java Program to Calculate Compound Interest
Compound interest is interest earned on the principal and on the interest added in earlier periods. Because the interest itself earns interest, the amount grows faster than with simple interest.
The final amount is:
A = P × (1 + r / n)n × t
Ais the final amount, including interest,Pis the principal,ris the yearly interest rate as a decimal (7.2% = 0.072),nis how many times interest is compounded per year (1 = yearly, 4 = quarterly, 12 = monthly),tis the time in years.
The compound interest is then A - P.
1. Compound Interest with User Input
Math.pow(base, exponent) calculates the power in the formula. The rate entered as a percentage is divided by 100 to turn it into a decimal.
import java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter the rate of interest (% per year): ");
double ratePercent = scanner.nextDouble();
System.out.print("Enter the time (in years): ");
double years = scanner.nextDouble();
System.out.print("Times interest is compounded per year: ");
int timesPerYear = scanner.nextInt();
scanner.close();
double rate = ratePercent / 100;
double amount = principal * Math.pow(1 + rate / timesPerYear, timesPerYear * years);
double interest = amount - principal;
System.out.printf("Final amount: %.2f%n", amount);
System.out.printf("Compound interest: %.2f%n", interest);
}
}
Output (with sample input)
Enter the principal amount: 500000 Enter the rate of interest (% per year): 7.2 Enter the time (in years): 5 Times interest is compounded per year: 4 Final amount: 714373.88 Compound interest: 214373.88
2. Compound vs Simple Interest Year by Year
This program compounds yearly and prints the balance at the end of each year next to the simple interest balance, so you can see the difference grow.
public class CompoundVsSimple {
public static void main(String[] args) {
double principal = 10000;
double rate = 0.08; // 8% per year
int years = 5;
System.out.println("Year Compound Simple");
double compound = principal;
for (int year = 1; year <= years; year++) {
compound *= (1 + rate); // add this year's interest
double simple = principal * (1 + rate * year);
System.out.printf("%4d %10.2f %10.2f%n", year, compound, simple);
}
}
}
Output
Year Compound Simple 1 10800.00 10800.00 2 11664.00 11600.00 3 12597.12 12400.00 4 13604.89 13200.00 5 14693.28 14000.00
3. Summary
- Compound interest adds interest to the balance, so later interest is earned on a larger amount.
- The final amount is
P * Math.pow(1 + r / n, n * t), withras a decimal. - Compound interest is the final amount minus the principal.
- Compounding more often (larger
n) gives a slightly higher amount.
Related Programs
Was this tutorial helpful?