Java Top

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

> CHECK OUT THE COURSE

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.

As always, the complete source code is available over on GitHub.

Java bottom

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

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!