Java Compound Interest

Implement the compound interest formula, which tells how money compounds as time passes.
Compound interest. Because of interest money compounds as time passes—we start earning interest on our interest. This can be computed with a Java method.
Monthly, quarterly, yearly. We can compound interest based on different schedules. And with a compound interest method, we can see the difference between these schedules.
A method. In researching compound interest, I found the formula on a University's page. I translated the formula into a Java method. We use addition, division, multiplication, and Math.pow.Math

Result: The compoundInterest method here returns the same results from the University page. So it is correct at least in that situation.

Compound Interest Formula:

Double: The method returns a double. This is important because the result almost always has a fractional part.

Java program that compounds interest public class Program { static double compoundInterest(double principal, double interestRate, int timesPerYear, double years) { // (1 + r/n) double body = 1 + (interestRate / timesPerYear); // nt double exponent = timesPerYear * years; // P(1 + r/n)^nt return principal * Math.pow(body, exponent); } public static void main(String[] args) { // Compound interest for four years quarterly. System.out.println(compoundInterest(1500, 0.043, 4, 6)); System.out.println(); // Compare monthly, quarterly, and yearly interest for 10 years. System.out.println(compoundInterest(1000, 0.2, 1, 10)); System.out.println(compoundInterest(1000, 0.2, 4, 10)); System.out.println(compoundInterest(1000, 0.2, 12, 10)); } } Output 1938.8368221341054 6191.7364223999975 7039.988712124658 7268.254992160187
Memoization. As with other mathematical computations, compound interest is a good opportunity to store and reuse results. This is called memoization.

And: A HashMap or array could be used. We can store either the entire result of compoundInterest or parts of it.

Schedules. Please look at the three final calls to compoundInterest. They use the same parameters but the 20% interest is compounded at different speeds—yearly, quarterly, and monthly.

Yearly: With interest just once a year, the money grows from 1,000 to 6,191. This is not as a high as quarterly or monthly.

Quarterly: Here the money grows to 7,039, which is nearly 1,000 more than yearly interest. You are on your way to riches.

Monthly: Here the results are even better. We end up with 7,268. But the difference is lessening.

Tip: This experiment can be applied in investing. A fund with quarterly interest (or dividends) may give a greater total return.

Computing interest. In volatile markets, interest rates may seem less important. But the fundamental way interest compounds upon itself is core to all simulations.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to