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

1. Overview

In this tutorial, we’ll discuss how to implement stateless objects in Java. Stateless objects are instances of classes with no instance fields.

In Java, all our code must go in a class. When writing an algorithm, we may only need to provide static methods within a class to achieve this.

However, there may be times when we wish to bind our algorithm to a stateless object.

2. Objects Overview Regarding State

When we think about objects in Java, we usually think about objects that contain state in fields, and methods which operate on that state to provide behaviour.

On top of that, we may make objects with unmodifiable fields. These have their state defined at creation time, and are then immutable as their state doesn’t change. In concurrent operations, immutable objects benefit from the same advantages as stateless objects.

Finally, we have objects that have either no fields at all or only compile-time constant fields. These objects are stateless.

Let’s look at why we may wish to use a stateless object.

3. Using a Stateless Object

For our example, let’s take a sorting algorithm that has no state. Let’s choose the Bubblesort as our implementation:

public void sort(int[] array) {
    int n = array.length;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j  array[j + 1]) {
                int swap = array[j];
                array[j] = array[j + 1];
                array[j + 1] = swap;
            }
        }
    }
}

3.1. Multiple Stateless Sorting Implementations

We now want to add the possibility to sort using other sorting algorithms, so we consider the Quicksort algorithm, which is also stateless:

public void sort(int[] array) {
    quickSort(array, 0, array.length - 1);
}
    
private void quickSort(int[] array, int begin, int end) {
    if (begin < end) {
        int pi = partition(array, begin, end);
        quickSort(array, begin, pi - 1);
        quickSort(array, pi + 1, end);
    }
}    

private int partition(int[] array, int low, int high) {
    int pivot = array[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (array[j] < pivot) {
            i++;
            int swap = array[i];
            array[i] = array[j];
            array[j] = swap;
        }
    }
    int swap = array[i + 1];
    array[i + 1] = array[high];
    array[high] = swap;
    return i + 1;
}

3.2. Choosing Between Implementations

Let’s say that the decision on which algorithm to use is made at runtime.

We need a way to select the right sorting algorithm at runtime. For this, there’s a design pattern we use called the Strategy design pattern.

To implement the Strategy pattern in our case, we’d create an interface called SortingStrategy that contains the signature of the sort() method:

public interface SortingStrategy {   
    public void sort(int[] array);
}

We can now implement each of our sorting strategies as stateless objects that implement this interface. This allows us to switch to whichever implementation we like, while our consuming code uses whichever sorting object is passed to it:

public class BubbleSort implements SortingStrategy {

    @Override
    public void sort(int[] array) {
        // Bubblesort implementation
    }
}

public class QuickSort implements SortingStrategy {

    @Override
    public void sort(int[] array) {
        // Quicksort implementation
    }
    // Other helpful methods
}

Here our classes contain no fields and therefore have no state. However, since there is an object, it can satisfy the common interface we’ve defined for all sorting algorithms – SortingStrategy.

3.3. Singleton Stateless Implementations

We want to introduce a way to provide the user with the chosen sorting strategy. Since the classes are stateless, we don’t need more than one instance from any of them. Therefore, we can do this using the Singleton design pattern.

We can achieve this pattern for instances of a strategy, by using Java enum.

Let’s switch from the class type to enum and add just one constant – INSTANCE. This constant is effectively a single stateless instance of that particular sorting algorithm. As enum can implement a Java interface, this is a neat way to provide a singleton of a strategy object:

public enum BubbleSort implements SortingStrategy {
    
    INSTANCE;

    @Override
    public void sort(int[] array) {
        // Bubblesort implementation
    }
}

public enum QuickSort implements SortingStrategy {
    
    INSTANCE;

    @Override
    public void sort(int[] array) {
        // Quicksort implementation
    }
    // Other helpful methods
}

3.4. Testing the Sorting Strategies

Finally, we write tests to make sure both sorting strategies work and can be easily maintained:

@Test
void givenArray_whenBubbleSorting_thenSorted() {
    int[] arrayToSort = {17, 6, 11, 41, 5, 3, 4, -9};
    int[] sortedArray = {-9, 3, 4, 5, 6, 11, 17, 41};
        
    SortingStrategy sortingStrategy = BubbleSort.INSTANCE;
    sortingStrategy.sort(arrayToSort);
    assertArrayEquals(sortedArray, arrayToSort);
}
    
@Test
void givenArray_whenQuickSortSorting_thenSorted() {
    int[] arrayToSort = {17, 6, 11, 41, 5, 3, 4, -9};
    int[] sortedArray = {-9, 3, 4, 5, 6, 11, 17, 41};
        
    SortingStrategy sortingStrategy = QuickSort.INSTANCE;
    sortingStrategy.sort(arrayToSort);
    assertArrayEquals(sortedArray, arrayToSort);
}

4. Conclusion

In this article, we explored stateless objects in the Java language.

We saw that stateless objects are useful for keeping algorithms that don’t require state and we also looked at how to implement the strategy pattern.

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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments