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. Overview

Static methods are common to most object-oriented programming languages, including Java. What differentiates static from instance methods is that they have no object that owns them. Instead, static methods are defined on the class level and can be used without creating instances.

In this tutorial, we’ll look at the definition of static methods in Java, as well as their limitations. Then we’ll look at common use cases for using static methods and recommend when it makes sense to apply them in our code.

Finally, we’ll see how to test static methods and how to mock them.

2. Static Methods

Instance methods are resolved polymorphically based on the runtime type of the object. On the other hand, static methods are resolved at compile-time based on the class in which they are defined.

2.1. Class-level

A static method in Java is a part of the class definition. We can define a static method by adding the static keyword to a method:

private static int counter = 0;

public static int incrementCounter() {
    return ++counter;
}

public static int getCounterValue() {
    return counter;
}

To access static methods, we use the class name followed by a dot and the name of the method:

int oldValue = StaticCounter.getCounterValue();
int newValue = StaticCounter.incrementCounter();
assertThat(newValue).isEqualTo(oldValue + 1);

We should note that this static method has access to the static state of the StaticCounter class. Often static methods are stateless, but they can work with class-level data as part of various techniques, including the singleton pattern.

Although it’s also possible to reference static methods using objects, this antipattern is often flagged as an error by tools such as Sonar.

2.2. Limitations

As static methods don’t operate on instance members, there are a few limitations we should be aware of:

  • A static method cannot reference instance member variables directly
  • A static method cannot call an instance method directly
  • Subclasses cannot override static methods
  • We cannot use keywords this and super in a static method

Each of the above results in a compile-time error. We should also note that if we declare a static method with the same name in a subclass, it doesn’t override but instead hides the base class method.

3. Use Cases

Let’s now have a look at common use cases when it makes sense to apply static methods in our Java code.

3.1. Standard Behaviour

Using static methods makes sense when we are developing methods with standard behavior that operates on their input arguments.

The String operations from Apache StringUtils are a great example of this:

String str = StringUtils.capitalize("baeldung");
assertThat(str).isEqualTo("Baeldung");

Another good example is the Collections class, as it contains common methods that operate on different collections:

List<String> list = Arrays.asList("1", "2", "3");
Collections.reverse(list);
assertThat(list).containsExactly("3", "2", "1");

3.2. Reuse Across Instances

A valid reason for using static methods is when we reuse standard behavior across instances of different classes.

For example, we commonly use Java Collections and Apache StringUtils in our domain and business classes:

utils_demo_class_diagram

As these functions don’t have a state of their own and are not bound to a particular part of our business logic, it makes sense to hold them in a module where they can be shared.

3.3. Not Changing State

Since static methods cannot reference instance member variables, they are a good choice for methods that don’t require any object state manipulation.

When we use static methods for operations where the state is not managed, then method calling is more practical. The caller can call the method directly without having to create instances.

When we share state by all instances of the class, like in the case of a static counter, then methods that operate on that state should be static. Managing a global state can be a source of errors, so Sonar will report a critical issue when instance methods write directly to static fields.

3.4. Pure Functions

A function is called pure if its return value depends only on the input parameters passed. Pure functions get all the data from their parameters and compute something from that data.

Pure functions do not operate on any instance or static variables. Therefore, executing a pure function should also have no side effects.

As static methods do not allow overriding and referencing instance variables, they are a great choice for implementing pure functions in Java.

4. Utility Classes

Since Java doesn’t have a specific type set aside for housing a set of functions, we often create a utility class. Utility classes provide a home for pure static functions. Instead of writing the same logic over and over, we can group together pure functions which we reuse throughout the project.

A utility class in Java is a stateless class that we should never instantiate. Therefore, it’s recommended to declare it final, so it cannot be subclassed (which wouldn’t add value). Also, in order to prevent anyone from trying to instantiate it, we can add a private constructor:

public final class CustomStringUtils {

    private CustomStringUtils() {
    }

    public static boolean isEmpty(CharSequence cs) { 
        return cs == null || cs.length() == 0; 
    }
}

We should note that all methods we put in the utility class should be static.

5. Testing

Let’s check how we can unit test and mock static methods in Java.

5.1. Unit Testing

Unit testing of well-designed, pure static methods with JUnit is quite simple. We can use the class name to call our static method and pass some test parameters to it.

Our unit under test will compute the result from its input parameters. Therefore, we can make assertions on the result and test for different input-output combinations:

@Test
void givenNonEmptyString_whenIsEmptyMethodIsCalled_thenFalseIsReturned() {
    boolean empty = CustomStringUtils.isEmpty("baeldung");
    assertThat(empty).isFalse();
}

5.2. Mocking

Most of the time, we don’t need to mock static methods, and we can simply use the real function implementation in our tests. The need to mock static methods typically hints at a code design issue.

If we must, then we can mock static functions using Mockito. However, we will need to add an additional mockito-inline dependency to our pom.xml:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>3.8.0</version>
    <scope>test</scope>
</dependency>

Now, we can use the Mockito.mockStatic method to mock invocations to static method calls:

try (MockedStatic<StringUtils> utilities = Mockito.mockStatic(StringUtils.class)) {
    utilities.when(() -> StringUtils.capitalize("karoq")).thenReturn("Karoq");

    Car car1 = new Car(1, "karoq");
    assertThat(car1.getModelCapitalized()).isEqualTo("Karoq");
}

6. Conclusion

In this article, we explored common use cases for using static methods in our Java code. We learned the definition of static methods in Java, as well as their limitations.

Also, we explored when it makes sense to use static methods in our code. We saw that static methods are a good choice for pure functions with standard behavior that are getting reused across instances but not changing their state. Finally, we looked at how to test and mock static methods.

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)