Compound Interest in Java
Calculate compound interest using principal, rate, time, and compounding frequency.
IntermediateModule 1: Basic Java ProgramsExample 13 of 20
compound-interest.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter principal: ");8 double p = sc.nextDouble();9 System.out.print("Enter annual rate of interest: ");10 double r = sc.nextDouble();11 System.out.print("Enter time (in years): ");12 double t = sc.nextDouble();13 System.out.print("Enter number of times interest applied per year: ");14 int n = sc.nextInt();1516 double amount = p * Math.pow(1 + (r / (100 * n)), n * t);17 double ci = amount - p;1819 System.out.println("Compound Amount = " + amount);20 System.out.println("Compound Interest = " + ci);2122 sc.close();23 }24}
Output
Enter principal: 1000 Enter annual rate of interest: 5 Enter time (in years): 2 Enter number of times interest applied per year: 1 Compound Amount = 1102.5 Compound Interest = 102.5
What's going on
We use the standard compound interest formula:
A = P (1 + r/(100n))^(nt) and CI = A - P.