What is the @NoArgsConstructor annotation in Lombok?

What is Lombok?

Project Lombok is a Java library that helps to reduce the boilerplate codeA section of code that is repeated in multiple places with a little variation. Java is a verbose language where repetitive code like getters, setters, and so on, can be avoided. Lombok reduces the boilerplate code with its annotations that get plugged during the build process.

We can easily add Lombok to the project as one of the dependencies.

For a Gradle project, add the following two lines to the dependencies section of the build.gradle file:

compileOnly 'org.projectlombok:lombok:1.18.22'
annotationProcessor 'org.projectlombok:lombok:1.18.22'

For a Maven project, add the following lines to the dependencies section of the pom.xml file:

<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
</dependencies>

@NoArgsConstructor annotation

The @NoArgsConstructor annotation is used to generate the no-argument constructor for a class. In this case, the class consists of final fields. Using this annotation makes the compiler throw a compile-time error. To overcome this, the annotation takes a parameter called force which, when set to true, initializes the final fields 0 or false or null.

Note: A no-argument constructor is a constructor with no parameters.

Code

The following code shows how the annotation reduces writing the no-arg constructor to a single annotation:

import lombok.NoArgsConstructor;
public class Main {
static class Person{
private int age;
public Person() {}
}
@NoArgsConstructor
static class NewPerson{
private int age;
}
}

Explanation

In the above code, we have two classes, Person and NewPerson. A no-arg constructor is written for the Person class in line 8.

The NewPerson class is annotated with @NoArgsConstructor annotation. The annotation generates the no-arg constructor for us.