Java Recursion

Today we are going to speak about Java recursion. Our sample code is a program that divides the given number by another number a fixed number of times.

Java Recursion –


public class RecursionSample {

   public static void main(String[] args) {
       double divideThis     = 1000;
       double divideby       = 2;
       long howManyTimes    = 10;
       System.out.println("The result of dividing " + divideThis + " by " + divideby + " " + howManyTimes + " is "
                           + divide(divideThis, divideby, howManyTimes));
   public static double divide(double what, double divideBy, long times) {
       double result = what/divideBy;
       if (times-- > 0)
           return divide(result, divideBy, times);
       return result;

This code divides 1000 by 2 10 times. The output is this.

The result of dividing 1000.0 by 2.0 10 is 0.48828125

The idea of recursion in Java is that a method is calling itself when a specific condition is meet – in our example until times variable is more than 0. If the condition is not met then all the method call stack is returning to the first method called. In our example the main method.
Every method call handler (the place in the code where a method was called) is being put on the stack. In our example the method call stack looks like this.

Java Recursion - Program execution stack

Java Recursion – Program execution stack

So when a method ends than each handler is taken (pop!) from the stack and the program is returning to the next program line available.


Sometimes while playing with the recursion you will end up with the java.lang.StackOverflowError. Try increasing the howManyTimes variable to 100000.

long howManyTimes = 100000;

Yep! The java.lang.StackOverflowError occurs. Java stack is limited by the memory settings. If you want to increase the memory size dedicated for the stack during runtime just use -Xss JVM parameter while running your program.

java -Xss4096k …

Download this sample code here.

This code is available on our GitHub repository as well.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>