eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

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.

2. Understand Recursion

2.1. The Definition

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.

2.2. Tail Recursion Versus Head Recursion

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.

2.3. Recursion Versus Iteration

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.

3. Examples

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

3.1. Finding N-Th Power of Ten

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;
}

3.2. Finding N-Th Element of Fibonacci Sequence

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: 0 1 1 2 3 5 8 13 21 34 55

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 Recursive Call.

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);
}

3.3. Converting from Decimal to Binary

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);
}

3.4. Height of a Binary Tree

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.

4. Conclusion

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

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)