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 – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

In this article, we’ll explain how to use the @Contract annotation. Thanks to this annotation, we can define a contract that our methods must match. JetBrains, the brand behind IntelliJ IDEA, introduced the annotation. It allows the text editor to directly troubleshoot potential problems with the calling methods in our code.

2. Setup Maven Dependency

The latest version of the annotations library can be found in the Maven Central Repository. Let’s add the dependency in our pom.xml:

<dependency>
    <groupId>org.jetbrains</groupId
    <artifactId>annotations</artifactId>
    <version>24.0.1</version>
</dependency>

3. The Value Attribute

The @Contract annotation has two attributes: value and pure. The value attribute contains clauses describing the relationship between the methods’ inputs and output. It’s the primary functionality of the annotation and was first introduced in IntelliJ 14.

3.1. Contract Grammar

A contract is a set of causality clauses of the form: “A -> B”. This means that providing A to the method will always give B as a result. For instance, “_ -> null” means that the method returns null for any input value.

The possible constraints on the input are the following:

  • _: any value
  • null: a null value
  • !null: a non-null value
  • true: a true boolean value
  • false: a false boolean value

The return value supports the same constraints as long as the following ones:

  • fail: the method throws an Exception
  • new: the method returns a new Object. This Object must be non-null and different from any other Object already present in the heap
  • this: the method returns its qualifier value. It can’t be applied to static methods
  • param1, param2, ..: the method returns the value of its first (respectively second…) parameter

The new, this, and param1 keywords have only been supported since IntelliJ 2018.2.

Additionally, let’s point out that various constraints can be accumulated as long as they don’t collide.

3.2. Writing Our First Contracts

Let’s now showcase a first example: we’ll create a Person class with a lone name attribute. We’ll add a builder method that will set the name of the Person and return the Person instance:

public class Person {

    String name;

    @Contract("_ -> this")
    Person withName(String name) {
        this.name = name;
        return this;
    }
}

As we can see, whatever the input is, the object itself is returned, so we annotated this method with the valid @Contract(“_ -> this”) annotation.

Let’s now write a method with a more complex signature. This method concatenates two Strings only if the second one is not null and returns null otherwise. Thus, we can give it a contract that states that:

  • if the second argument is null, the result is null and doesn’t depend on the value of the first argument
  • if the first argument is null, the result is the value of the second argument
  • if the second argument isn’t null, then the result isn’t null

In a nutshell, we can annotate our method with the following contract:

@Contract("_, null -> null; null, _ -> param2; _, !null -> !null")
String concatenateOnlyIfSecondArgumentIsNotNull(String head, String tail) {
    if (tail == null) {
        return null;
    }
    if (head == null) {
        return tail;
    }
    return head + tail;
}

3.3. Code Inspection

Writing a contract can result in two types of errors:

  • the contract isn’t written correctly
  • a calling method has some unreachable code

IntelliJ can run code analysis and highlight both kinds of errors. To run the code inspection, we can open the Code menu and then choose Inspect Code:

 

inspect code intellij

For instance, let’s write a method that doesn’t do anything. We’ll add a wrong contract that states that it should always fail:

@Contract(" -> fail")
void doNothingWithWrongContract() {}

The Problems tab opens, and the editor warns us about a probable bug in the code:

 

violated contract clause

Those hints that concern contract correctness are useful, but the inspection tool really shines when it helps to remove dead or redundant code. For example, let’s write a piece of code that will call the concatenateOnlyIfSecondArgumentIsNotNull method for two non-null Strings. Then, we’ll want to print the result if it’s not null. Naively, we could write:

String concatenation = concatenateOnlyIfSecondArgumentIsNotNull("1234", "5678");
if (concatenation != null) {
    System.out.println(concatenation);
}

Let’s run the code inspection tool. The following message appears:

Condition 'concatenation != null' is always 'true'

Our non-null check is indeed redundant because calling concatenateOnlyIfSecondArgumentIsNotNull on two non-null arguments will always return a non-null result. And IntelliJ was able to spot that thanks to the @Contract annotation!

Last but not least, let’s mention that IntelliJ is also able to carefully look at our libraries’ bytecode and infer contract annotations. For instance, IntelliJ automatically annotates the isEmpty() method with @Contract(“null->true”).

4. The Pure Attribute

The pure attribute specifies that the method has no visible side effects. Thus, if the return value of a pure method isn’t used, we’ll be able to safely remove the call without changing the overall result of our code. Printing to the standard output isn’t considered a visible side effect. On the other hand, methods that don’t seem to have a side effect but could allow changes happening in other threads to be visible in their thread after their execution can’t be marked as pure.

For instance, replacing some characters in a String is a pure operation:

@Contract(pure = true)
String replace(String string, char oldChar, char newChar) {
    return string.replace(oldChar, newChar);
}

Furthermore, it is possible to use the pure attribute alongside the value attribute. For instance, we can write a not method that returns the opposite of its boolean parameter with the following contract:

@Contract(value = "true -> false; false -> true", pure = true)
boolean not(boolean input) {
    return !input;
}

As of version 2023.1, IntelliJ doesn’t run any relevant code inspection based on the pure attribute. The default value for the pure attribute is false.

6. Conclusion

In this tutorial, we’ve seen how to use the @Contract annotation. Adding this annotation to our toolbox can significantly impact our code quality. In particular, we can easily spot dead code thanks to the value attributes. However, we need to point out that the annotation is just here for description purposes and doesn’t have any consequence on the compiled code.

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.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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