Java Program to Calculate Compound Interest

This article is created to cover a program in Java that find and prints compound interest based on the data provided by user at run-time of the program.

The formula to find compound interest is:

CI = (1 + r/n)(nt) - p

where CI indicates to Compound Interest, p indicates to Principal Amount, r indicates to the Annual Rate of Interest, t is Time Period for which the money is invested or borrowed, and n indicates to the Number of Times that the interest is compounded per unit t.

Note - If the interest is compounded monthly, then the value of n would be 12. If the interest is compounded quarterly, then the value of n would be 4, and so on. This happens when t is in years.

The question is, write a Java program to find and print the compound interest based on the data such as p, r, t, and n values. The data must be received by user at run-time of the program. The program given below is its answer:

import java.util.Scanner;

public class fresherearth
{
   public static void main(String[] args)
   {
      double p, r, t, n, ci;
      Scanner s = new Scanner(System.in);
      
      System.out.print("Enter the Value of p (Principal Amount): ");
      p = s.nextDouble();
      System.out.print("Enter the Value of r (Annual Rate of Interest): ");
      r = s.nextDouble();
      System.out.print("Enter the Value of t (Time Period): ");
      t = s.nextDouble();
      System.out.print("Enter the Value of n (Number of Times, Interest is Compounded): ");
      n = s.nextDouble();
      
      ci = p * Math.pow(1 + (r/n), (n*t)) - p;
      
      System.out.println("\nCompound Interest = " +ci);
   }
}

The snapshot given below shows the sample run of above Java program with user inputs 10000 as principal amount, 3.5 as rate of interest, 5 as time period, and 12 as number of times that the interest is compounded:

java calculate compound interest

The above program can also be created in this way. This program prints the value of Amount too.

import java.util.Scanner;

public class fresherearth
{
   public static void main(String[] args)
   {
      Scanner s = new Scanner(System.in);
      
      System.out.print("Enter the Value of p: ");
      float p = s.nextFloat();
      System.out.print("Enter the Value of r: ");
      float r = s.nextFloat();
      System.out.print("Enter the Value of t: ");
      float t = s.nextFloat();
      System.out.print("Enter the Value of n: ");
      float n = s.nextFloat();
      
      float amount = p * (float)Math.pow(1 + (r/n), (n*t));
      float ci = amount - p;
      
      System.out.println("\nAmount = " +amount);
      System.out.println("Compound Interest = " +ci);
   }
}

Here is its sample run with user input 10000 as p, 0.08 as r, 1 as t, and 12 as n:

find compound interest in Java

Java Online Test


« Previous Program Next Program »