**I just announced the new *** Learn Spring * course, focused on the fundamentals of Spring 5 and Spring Boot 2:

*Learn Spring*course, focused on the fundamentals of Spring 5 and Spring Boot 2:

**>> CHECK OUT THE COURSE**

Last modified: May 7, 2019

In this article, we'll focus on a core concept in any programming language – recursion.

We'll explain the characteristics of a *recursive function *and show how to use recursion for solving various problems in Java.

In Java, the function-call mechanism supports **the possibility of having a method call itself**. This functionality is known as *recursion**. *

For example, suppose we want to sum the integers from 0 to some value *n*:

public int sum(int n) { if (n >= 1) { return sum(n - 1) + n; } return n; }

There are two main requirements of a recursive function:

**A Stop Condition**– the function returns a value when a certain condition is satisfied, without a further recursive call**The Recursive Call**– the function calls itself with an*input*which is a step closer to the stop condition

Each recursive call will add a new frame to the stack memory of the JVM. So, **if we don't pay attention to how deep our recursive call can dive, an out of memory exception may occur. **

This potential problem can be averted by leveraging tail-recursion optimization.

We refer to a recursive function as *tail-recursion* **when the recursive call is the last thing that function executes.** Otherwise, it's known as *head-recursion*.

Our implementation above of the *sum()* function is an example of head recursion and can be changed to tail recursion:

public int tailSum(int currentSum, int n) { if (n <= 1) { return currentSum + n; } return tailSum(currentSum + n, n - 1); }

With tail recursion, **the recursive call is the last thing the method does, so there is nothing left to execute within the current function.**

Thus, logically there is no need to store current function's stack frame.

Although the compiler *can* utilize this point to optimize memory, it should be noted that the **Java compiler doesn't optimize for tail-recursion for now**.

Recursion can help to simplify the implementation of some complicated problems by making the code clearer and more readable.

But as we've already seen the recursive approach often requires more memory as the stack memory required increases with each recursive call.

As an alternative, if we can solve a problem with recursion, we can also solve it by iteration.

For example, our *sum* method could be implemented using iteration:

public int iterativeSum(int n) { int sum = 0; if(n < 0) { return -1; } for(int i=0; i<=n; i++) { sum += i; } return sum; }

In comparison to recursion, the iterative approach could potentially give better performance. That being said, iteration will be more complicated and harder to understand compared to recursion, for example: traversing a binary tree.

Making the right choice between head recursion, tail recursion and an iterative approach all depend on the specific problem and situation.

Now, let's try to resolve some problems in a recursive way.

Suppose we need to calculate the *n*-th power of 10. Here our input is *n.* Thinking in a recursive way, we can calculate *(n-1)*-th power of 10 first, and multiply the result by 10.

Then, to calculate the *(n-1)*-th power of 10 will be the *(n-2)*-th power of 10 and multiply that result by 10, and so on. We'll continue like this until we get to a point where we need to calculate the (n-n)-th power of 10, which is 1.

If we wanted to implement this in Java, we'd write:

public int powerOf10(int n) { if (n == 0) { return 1; } return powerOf10(n-1) * 10; }

Starting with *0* and *1*, **the Fibonacci Sequence is a sequence of numbers where each number is defined as the sum of the two numbers proceeding it**:

So, given a number *n*, our problem is to find the *n*-th element of *Fibonacci Sequence*. **To implement a recursive solution, we need to figure out the Stop Condition and the **

Luckily, it's really straightforward.

Let's call *f(n)* the *n*-th value of the sequence. Then we'll have *f(n) = f(n-1) + f(n-2)* (the *Recursive Call*)*. *

Meanwhile, *f(0) = 0 * and *f(1) = 1* ( *Stop Condition)*.

Then, it's really obvious for us to define a recursive method to solve the problem:

public int fibonacci(int n) { if (n <= 1) { return n; } return fibonacci(n-1) + fibonacci(n-2); }

Now, let's consider the problem of converting a decimal number to binary. The requirement is to implement a method which receives a positive integer value *n* and returns a binary *String* representation.

One approach to converting a decimal number to binary is to divide the value by 2, record the remainder and continue to divide the quotient by 2.

We keep dividing like that until we get a quotient of *0*. Then, by writing out all of the remainders in reserve order, we obtain the binary string.

Hence, our problem is to write a method that returns these remainders in reserve order:

public String toBinary(int n) { if (n <= 1 ) { return String.valueOf(n); } return toBinary(n / 2) + String.valueOf(n % 2); }

The height of a binary tree is defined as the number of edges from the root to the deepest leaf. Our problem now is to calculate this value for a given binary tree.

One simple approach would be to find the deepest leaf then counting the edges between the root and that leaf.

But trying to think of a recursive solution, we can restate the definition for the height of a binary tree as the max height of the root's left branch and the root's right branch, plus *1*.

If the root has no left branch and right branch, its height is *zero*.

Here is our implementation:

public int calculateTreeHeight(BinaryNode root){ if (root!= null) { if (root.getLeft() != null || root.getRight() != null) { return 1 + max(calculateTreeHeight(root.left), calculateTreeHeight(root.right)); } } return 0; }

Hence, we see that **some problems can be solved with recursion in a really simple way.**

In this tutorial, we have introduced the concept of recursion in Java and demonstrated it with a few simple examples.

The implementation of this article can be found over on Github.

Love the solution for finding the height of a binary tree