Calculate Compound Interest in Java

Exercise:

Write a Java Program to calculate compound interest.

Click Here to View the Solution!
import java.util.Scanner;

public class CompoundInterest {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // taking values from users
        System.out.print("Principal: ");
        double principal = input.nextDouble();
        System.out.print("Rate: ");
        double rate = input.nextDouble();
        System.out.print("Time: ");
        double time = input.nextDouble();
        System.out.print("Number of times interest is compounded: ");
        int number = input.nextInt();

        // Formula to calculate Compound Interest
        double interest = principal * (Math.pow((1 + rate/100), (time * number))) - principal;
        System.out.println("Compound Interest: " + interest);
        input.close();
    }
}
Click Here to View the Output!
Principal: 50000                                               
Rate: 12                                                       
Time: 3                                                        
Number of times interest is compounded: 3                      
Compound Interest: 88653.93787250947 
Click Here to View the Explanation!
  • This program is used to perform the calculation of compound interest using a formula and Java methods.
  • Initially, a Scanner object of the Scanner class is created that is used to take input from the user.
  • The program will request the user to enter the values of principal, rate, time and the number of times the interest is to be compounded. And store their values in variables principal, rate and time of type double and number of type int.
  • Finally, a formula to calculate the compound interest is stored in the variable interest as follows: Interest = principal * (Math.pow((1 + rate/100), (time * number))) – principal
  • The Math.pow() method is used to calculate a value raise to the power of another value.
  • Finally, the output is printed on the screen.
%d bloggers like this: