Lombok
Reduce boilerplate with @Getter, @Setter, @Builder, @Data, @Slf4j and more
- Eliminate boilerplate getters, setters, and constructors with Lombok annotations
- Build fluent APIs using @Builder and @SuperBuilder
- Understand which Lombok annotations are safe in production
A professional-quality reference covering every Lombok feature discussed in the lecture, with deep explanations, code examples, diagrams, and interview notes.
Table of Contents
- What is Lombok?
- Setup & Configuration
- Feature 1 —
valandvar - Feature 2 —
@NonNull - Feature 3 —
@Getterand@Setter - Feature 4 —
@ToString - Feature 5 —
@NoArgsConstructor,@RequiredArgsConstructor,@AllArgsConstructor - Feature 6 —
@EqualsAndHashCode - Feature 7 —
@Data - Feature 8 —
@Value - Feature 9 —
@Builder - Feature 10 —
@Cleanup - Quick Reference Table
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. What is Lombok?
Overview
Project Lombok is a Java library that significantly reduces the amount of repetitive, boilerplate code that Java developers must write. It works through Java's annotation processing mechanism — you annotate your classes or fields with Lombok-specific annotations, and during the compilation phase, Lombok reads those annotations and automatically injects the corresponding code into your compiled .class files.
The result: your source code stays lean and readable while the bytecode contains all the necessary methods.
Why This Concept Exists
Java is an expressive, strongly typed language — but that comes at a cost. A typical Plain Old Java Object (POJO) requires:
- Private fields
- A no-argument constructor
- Getters and setters for every field
- A meaningful
toString()method - Correct
equals()andhashCode()implementations
For a class with just five fields, this can balloon to 80–100 lines of code where the actual business logic is zero lines. Critics of Java often cite this as "Java verbosity."
Lombok was created as a direct answer to this criticism. Its goal is to let you write only what matters — the fields and the logic — and let the library generate the rest.
Definition
Lombok
is a Java annotation-processing library that generates boilerplate code (getters, setters, constructors, equals, hashCode, toString, and more) at compile time by processing annotations placed on classes and fields.
Key Facts
| Property | Detail |
|---|---|
| Type | Java library (annotation processor) |
| Compatible with | Java 6 and all later versions |
| How it works | Code injection at compile time via annotation processing |
| Impact on runtime | Zero — no runtime dependency needed in production |
| Maven artifact | org.projectlombok:lombok |
Real-world Analogy
Imagine a construction crew where instead of laying every brick manually, an automated brick-laying machine does it for you. You just specify the blueprint (annotations), and the machine fills in all the standard work (boilerplate). Your blueprint document remains short and clean, while the actual building (.class file) is complete.
How Lombok Works Internally Compile-Time Code Injection
1Your source code (.java)2 │3 ▼4Java Compiler invokes annotation processors5 │6 ▼7Lombok reads your annotations8 │9 ▼10Lombok injects AST (Abstract Syntax Tree) nodes into the compilation unit11 │12 ▼13Compiler finishes compiling14 │15 ▼16.class file contains all the generated methods.java source file. Your source stays clean; only the compiled output changes.2. Setup & Configuration
Step 1 Add Maven Dependency
Add the Lombok dependency to your pom.xml. Always use the latest stable version.
1<dependency>2 <groupId>org.projectlombok</groupId>3 <artifactId>lombok</artifactId>4 <version>1.18.32</version> <!-- use latest -->5 <scope>provided</scope>6</dependency>provided means Lombok is only needed at compile time. It does not need to be bundled in your production JAR — because by then its job is already done.Step 2 Install the IDE Plugin
Without the IDE plugin, your editor will show red underlines and false compilation errors — even though the code compiles and runs correctly. This happens because:
- Lombok injects code at compile time
- Your IDE's real-time analysis doesn't run the full compiler
- The IDE doesn't know what Lombok is about to generate
In IntelliJ IDEA:
- Open
Settings→Plugins - Search for "Lombok"
- Install the plugin
- Restart the IDE
Step 3 Enable Annotation Processing
Even with the plugin installed, the IDE needs to be told to run annotation processors during its incremental builds.
In IntelliJ IDEA:
- Open
Settings→Build, Execution, Deployment→Compiler→Annotation Processors - Check "Enable annotation processing"
- Apply and OK
3. Feature 1 `val` and `var`
Overview
val and var are Lombok's local variable type inference keywords. Instead of explicitly declaring the type of a local variable, you use val or var and let Lombok (and the compiler) figure out the type from the assigned value (the initializer expression).
Definition
| Keyword | Behavior |
|---|---|
val | Infers type from initializer; makes the variable final (immutable) |
var | Infers type from initializer; does not make the variable final (mutable) |
val and var work only on local variables — variables declared inside a method body or block. They cannot be used for:
- Class fields (instance or static variables)
- Method parameters
- Return typesWhy This Exists
In verbose Java code, you often write the type twice:
1// Traditional Java — type repeated2ArrayList<String> names = new ArrayList<String>();With val or var, you eliminate this redundancy. The type is obvious from the right-hand side — no need to repeat yourself.
Syntax
1import lombok.val;2import lombok.var;3
4val variableName = initializerExpression; // final, type inferred5var variableName = initializerExpression; // mutable, type inferredCode Example
1import lombok.val;2import lombok.var;3
4public class ValVarExample {5 public void demonstrate() {6 // val — inferred as int, made final7 val a = 10;8 // a = 20; // ❌ Compile error: cannot assign to final variable9
10 // val — inferred as String, made final11 val greeting = "Hello";12 System.out.println(greeting); // Hello13
14 // var — inferred as int, NOT final15 var count = 5;16 count = 10; // ✅ Allowed — var is mutable17 System.out.println(count); // 1018
19 // val with a List — type inferred20 val names = new java.util.ArrayList<String>();21 names.add("Alice");22 names.add("Bob");23 System.out.println(names); // [Alice, Bob]24 }25}What the Compiled `.class` Looks Like
When you use val a = 10;, Lombok rewrites it in the bytecode as:
1final int a = 10;And var greeting = "Hello" becomes:
1String greeting = "Hello";The types are determined from the right-hand side. The IDE plugin shows you these inferred types inline.
Key Observations
valis equivalent to writingfinal+ the inferred typevaris equivalent to writing just the inferred type (nofinal)- The inference happens at compile time — there is no runtime overhead
- Cannot be used for fields, parameters, or return types
val and var in red, claiming a compilation error. The code will still compile and run correctly because Lombok handles it at compile time. Install the plugin to fix false IDE errors.4. Feature 2 `@NonNull`
Overview
@NonNull is a parameter/field annotation that instructs Lombok to automatically generate a null check at the top of the method or constructor. If a null value is passed for a parameter annotated with @NonNull, a NullPointerException is thrown immediately with a descriptive message.
Why This Exists
Null pointer exceptions are among the most common bugs in Java. Without @NonNull, developers must write null checks manually:
1public void greet(String name) {2 if (name == null) {3 throw new NullPointerException("name is marked non-null but is null");4 }5 System.out.println("Hello, " + name);6}This is repetitive. @NonNull generates this check automatically.
Definition
@NonNullcauses Lombok to insert a null check as the first statement of the method or constructor body. If the annotated parameter isnull, aNullPointerExceptionis thrown before any other logic executes.
Usage Scope
| Usage location | Supported? |
|---|---|
| Method parameter | ✅ Yes |
| Constructor parameter | ✅ Yes |
| Field (with constructor annotations) | ✅ Yes (generates null check in constructor) |
| Return type | ❌ No |
Syntax
1import lombok.NonNull;2
3public void methodName(@NonNull ParameterType paramName) {4 // Lombok inserts null check here automatically5 // Your logic here6}Code Example Source Code
1import lombok.NonNull;2
3public class NonNullExample {4
5 public void greet(@NonNull String name) {6 System.out.println("Hello, " + name);7 }8
9 public static void main(String[] args) {10 NonNullExample ex = new NonNullExample();11 ex.greet("Alice"); // Prints: Hello, Alice12 ex.greet(null); // Throws NullPointerException13 }14}What Lombok Generates (Compiled `.class`)
1public void greet(String name) {2 if (name == null) {3 throw new NullPointerException("name is marked non-null but is null");4 }5 System.out.println("Hello, " + name);6}Lombok adds the null check as the very first statement inside the method body.
Output
1Hello, Alice2Exception in thread "main" java.lang.NullPointerException: name is marked non-null but is null3 at NonNullExample.greet(NonNullExample.java:5)4 at NonNullExample.main(NonNullExample.java:11)Key Observations
- The null check is always inserted before any user-written logic
- The exception message includes the parameter name, making debugging easy
- Works seamlessly with constructor annotations (
@AllArgsConstructor, etc.) — more on this in Feature 5
5. Feature 3 `@Getter` and `@Setter`
Overview
@Getter and @Setter are Lombok's most widely used annotations. They automatically generate the standard getXxx() and setXxx() methods for your fields, following Java naming conventions (with isXxx() for boolean fields).
Why This Exists
Every POJO class in Java requires getters and setters — sometimes dozens of them. Writing them by hand is tedious, error-prone (typos in method names), and inflates your source files with non-logic code.
Definition
| Annotation | What it generates |
|---|---|
@Getter on a field | A getFieldName() method (or isFieldName() for boolean) |
@Setter on a field | A setFieldName(Type value) method |
@Getter on a class | @Getter applied to all non-static fields |
@Setter on a class | @Setter applied to all non-static, non-final fields |
Default Access Level
By default, Lombok generates getter and setter methods as public.
Syntax Field Level
1import lombok.Getter;2import lombok.Setter;3
4public class Person {5
6 @Getter @Setter7 private String name;8
9 @Getter @Setter10 private boolean committeeMemeber;11}What Lombok Generates
1public String getName() {2 return this.name;3}4
5public void setName(String name) {6 this.name = name;7}8
9public boolean isCommitteeMember() {10 return this.committeeMember;11}12
13public void setCommitteeMember(boolean committeeMember) {14 this.committeeMember = committeeMember;15}boolean fields, the getter is prefixed with is (not get). This follows the Java Bean specification.Controlling Access Level
You can override the default public access level for any getter or setter:
1import lombok.AccessLevel;2import lombok.Getter;3import lombok.Setter;4
5public class Person {6
7 @Getter(AccessLevel.PRIVATE)8 @Setter(AccessLevel.PROTECTED)9 private String name;10
11 // No access level specified — defaults to PUBLIC12 @Getter @Setter13 private boolean committeeMember;14}Available access levels:
AccessLevel constant | Java visibility |
|---|---|
PUBLIC | public (default) |
PROTECTED | protected |
PACKAGE | package-private (no keyword) |
PRIVATE | private |
NONE | Do not generate this method |
Class-Level Usage
Apply @Getter or @Setter to the entire class to generate methods for all eligible fields at once:
1import lombok.Getter;2import lombok.Setter;3
4@Getter5@Setter6public class Employee {7 private String name;8 private boolean committeeMember;9 private static int totalCount; // static — no getter/setter generated10 private final String id = "E001"; // final — no setter generated11}Rules for Class-Level Annotations
| Field type | @Getter generates getter? | @Setter generates setter? |
|---|---|---|
| Non-static, non-final | ✅ Yes | ✅ Yes |
| Static | ❌ No | ❌ No |
| Final (non-static) | ✅ Yes | ❌ No (can't reassign final) |
Skipping a Specific Field with `AccessLevel.NONE`
When using class-level annotations, you can exclude specific fields:
1@Getter2@Setter3public class Employee {4 private String name;5
6 @Setter(AccessLevel.NONE) // No setter for this field7 private boolean committeeMember;8}This overrides the class-level @Setter for committeeMember, suppressing setter generation for just that field.
Diagrams
Static fields and final fields get no setters. Final fields still get a getter. Static fields get nothing.
6. Feature 4 `@ToString`
Overview
@ToString generates a toString() method for your class. This is extremely useful for logging and debugging — it gives you a human-readable string representation of an object's state without writing the method yourself.
Why This Exists
The default toString() inherited from Object returns something like com.example.Person@3764951d — the class name and memory address hash. This is useless for debugging. Every POJO should override toString(), but writing it manually is repetitive.
Default Format
1ClassName(field1=value1, field2=value2, ...)Syntax
1import lombok.ToString;2
3@ToString4public class Person {5 private String name;6 private boolean committeeMember;7}Generated Method (Default)
1@Override2public String toString() {3 return "Person(name=" + this.name + ", committeeMember=" + this.committeeMember + ")";4}Configuration Options
Excluding Specific Fields
Use @ToString.Exclude on any field you don't want in the output (e.g., sensitive data, passwords, large objects):
1@ToString2public class Person {3 private String name;4
5 @ToString.Exclude6 private boolean committeeMember; // Won't appear in toString output7}@ToString(includeFieldNames = false)
public class Person {
private String name;
private boolean committeeMember;
}Output: Person(Alice, true)
Explicitly Selecting Fields
Include only fields you explicitly mark, ignoring all others:
1@ToString(onlyExplicitlyIncluded = true)2public class Person {3 @ToString.Include4 private String name;5
6 private boolean committeeMember; // Not included — not marked7}import lombok.*;
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
public class Employee {
private String name;
private boolean committeeMember;
@NonNull
private Integer age;
}Generated Constructors
1. @NoArgsConstructor
1public Employee() {2}2. @AllArgsConstructor
1public Employee(String name, boolean committeeMember, Integer age) {2 if (age == null) {3 throw new NullPointerException("age is marked non-null but is null");4 }5 this.name = name;6 this.committeeMember = committeeMember;7 this.age = age;8}Notice: becauseageis@NonNull, a null check is automatically inserted in the all-args constructor too.
3. @RequiredArgsConstructor
1public Employee(@NonNull Integer age) {2 if (age == null) {3 throw new NullPointerException("age is marked non-null but is null");4 }5 this.age = age;6}Only age appears — because it is the only final or @NonNull field.
How `@NonNull` Interacts with Constructor Annotations
This is a frequently asked interview point. @NonNull can be placed on a field, and when combined with constructor-generating annotations, Lombok will:
- Include that field as a constructor parameter (in
@RequiredArgsConstructorand@AllArgsConstructor) - Insert a null check at the top of the constructor
Diagram
8. Feature 6 `@EqualsAndHashCode`
Overview
@EqualsAndHashCode generates equals(Object o) and hashCode() methods that follow the equals-hashCode contract required by Java's Object specification.
Why This Exists
Correctly implementing equals() and hashCode() together is notoriously tricky in Java:
- They must be consistent — if two objects are equal (
equals()returnstrue), they must have the samehashCode() - Forgetting to update one when fields change is a common, hard-to-debug bug
- Used extensively by
HashMap,HashSet,LinkedHashMap— getting it wrong causes silent data loss
HashMap uses it internally, consult the Java HashMap Internal Working topic.Default Behavior
By default, @EqualsAndHashCode uses all non-static, non-transient fields for both equals() and hashCode().
Syntax
1import lombok.EqualsAndHashCode;2
3@EqualsAndHashCode4public class Person {5 private String name;6 private boolean committeeMember;7 private static int count; // static — excluded automatically8}Excluding Specific Fields
1@EqualsAndHashCode2public class Person {3 private String name;4
5 @EqualsAndHashCode.Exclude6 private boolean committeeMember; // Excluded from equals and hashCode7}Generated Methods
1@Override2public boolean equals(Object o) {3 if (o == this) return true;4 if (!(o instanceof Person)) return false;5 final Person other = (Person) o;6 if (!other.canEqual((Object) this)) return false;7 final Object this$name = this.name;8 final Object other$name = other.name;9 if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;10 return true;11}12
13@Override14public int hashCode() {15 final int PRIME = 59;16 int result = 1;17 final Object $name = this.name;18 result = result * PRIME + ($name == null ? 43 : $name.hashCode());19 return result;20}The generated code correctly handles null fields and follows the equals-hashCode contract.
Exclusion/Inclusion Rules Summary
| Field type | Included by default? |
|---|---|
| Non-static, non-transient | ✅ Yes |
| Static | ❌ No |
| Transient | ❌ No |
Fields marked @EqualsAndHashCode.Exclude | ❌ No |
9. Feature 7 `@Data`
Overview
@Data is a convenience shortcut annotation that bundles several Lombok annotations together into one. It is the most commonly used Lombok annotation in production code.
Definition
1@Data = @ToString2 + @EqualsAndHashCode3 + @Getter (on all fields)4 + @Setter (on all non-final fields)5 + @RequiredArgsConstructorSyntax
1import lombok.Data;2import lombok.NonNull;3
4@Data5public class Employee {6 private String name;7 private final int age; // final — getter only, no setter8 @NonNull private String address; // @NonNull — in RequiredArgsConstructor9}What Lombok Generates
From this single @Data annotation, Lombok generates:
| Generated method | Reason |
|---|---|
toString() | From @ToString |
equals() and hashCode() | From @EqualsAndHashCode |
getName(), getAge(), getAddress() | Getters for all fields |
setName(String) | Setter for name (non-final) |
setAddress(String) | Setter for address (non-final, but with null check from @NonNull) |
(no setter for age) | age is final — no setter |
Constructor with age and address | @RequiredArgsConstructor — final + @NonNull fields |
Generated Code (Compiled `.class`)
1// toString2public String toString() {3 return "Employee(name=" + this.name + ", age=" + this.age + ", address=" + this.address + ")";4}5
6// equals and hashCode (following contract)7// ... (standard implementation using all non-static fields)8
9// Getters10public String getName() { return this.name; }11public int getAge() { return this.age; }12public String getAddress() { return this.address; }13
14// Setters (non-final fields only)15public void setName(String name) { this.name = name; }16public void setAddress(@NonNull String address) {17 if (address == null) throw new NullPointerException("address is marked non-null but is null");18 this.address = address;19}20
21// RequiredArgsConstructor22public Employee(int age, @NonNull String address) {23 if (address == null) throw new NullPointerException("address is marked non-null but is null");24 this.age = age;25 this.address = address;26}Diagram
@Data is a very powerful shortcut but can cause issues in inheritance hierarchies. Child classes that use @Data may have incorrect equals() implementations. Prefer explicit annotations or @EqualsAndHashCode(callSuper = true) in such cases.10. Feature 8 `@Value`
Overview
@Value is the immutable counterpart of @Data. It generates all the same methods but applies immutability constraints to the class and all its fields.
Definition
1@Value = @ToString2 + @EqualsAndHashCode3 + @Getter (all fields)4 + NO @Setter (immutable — no setters generated)5 + @AllArgsConstructor (because all fields become final)6 + Makes class `final` (cannot be subclassed)7 + Makes all fields `private final`Key Differences: `@Data` vs `@Value`
| Feature | @Data | @Value |
|---|---|---|
| Fields | Mutable (unless individually final) | All made private final |
| Setters | Generated for non-final fields | ❌ Not generated |
| Class modifier | Not final | Made final (cannot extend) |
| Constructor | @RequiredArgsConstructor | @AllArgsConstructor (all fields are final) |
| Use case | Mutable POJO | Immutable value object |
Why `@Value` Uses `@AllArgsConstructor`
Since @Value makes all fields final, every field must be set in the constructor (there are no setters). A @RequiredArgsConstructor that only includes final fields is effectively the same as an @AllArgsConstructor when all fields are final.
Code Example
1import lombok.Value;2
3@Value4public class Coordinate {5 double latitude;6 double longitude;7 String label;8}Usage:
1Coordinate coord = new Coordinate(28.61, 77.20, "New Delhi");2System.out.println(coord.getLatitude()); // 28.613System.out.println(coord); // Coordinate(latitude=28.61, longitude=77.20, label=New Delhi)4// coord.setLatitude(0.0); ❌ No setter existsGenerated `.class` (Conceptual)
1public final class Coordinate {2 private final double latitude;3 private final double longitude;4 private final String label;5
6 public Coordinate(double latitude, double longitude, String label) {7 this.latitude = latitude;8 this.longitude = longitude;9 this.label = label;10 }11
12 public double getLatitude() { return this.latitude; }13 public double getLongitude() { return this.longitude; }14 public String getLabel() { return this.label; }15
16 // toString, equals, hashCode generated following contract17}Real-World Use Case
@Value is ideal for:
- DTOs (Data Transfer Objects) that should not be modified after creation
- Value objects in Domain-Driven Design (DDD)
- Configuration objects that are set once and read many times
11. Feature 9 `@Builder`
Overview
@Builder implements the Builder design pattern automatically. It is used to construct objects piece by piece and is especially useful when a class has many fields, some of which are optional.
Why This Exists
Constructor calls with many parameters are hard to read:
1// Which argument is which? Hard to tell!2Employee emp = new Employee("Alice", 30, true, "Engineering", "New York", 75000.0);The Builder pattern makes object creation readable and flexible:
1Employee emp = Employee.builder()2 .name("Alice")3 .age(30)4 .committeeMember(true)5 .department("Engineering")6 .build();Two purposes of Builder Pattern
- Part-by-part object construction — Set only the fields you need, in any order
- Achieving immutability — The built object has no setters; once
build()is called, the object cannot change
Syntax
1import lombok.Builder;2
3@Builder4public class Employee {5 private String name;6 private int age;7 private String department;8}What Lombok Generates
Lombok generates an inner static Builder class:
1public class Employee {2 private String name;3 private int age;4 private String department;5
6 // Private all-args constructor (called only by Builder)7 private Employee(String name, int age, String department) { ... }8
9 // Static builder() factory method10 public static EmployeeBuilder builder() {11 return new EmployeeBuilder();12 }13
14 // Inner Builder class15 public static class EmployeeBuilder {16 private String name;17 private int age;18 private String department;19
20 public EmployeeBuilder name(String name) {21 this.name = name;22 return this; // returns Builder — enables method chaining23 }24
25 public EmployeeBuilder age(int age) {26 this.age = age;27 return this;28 }29
30 public EmployeeBuilder department(String department) {31 this.department = department;32 return this;33 }34
35 public Employee build() {36 return new Employee(name, age, department);37 }38 }39}Usage
1Employee emp = Employee.builder()2 .name("Alice")3 .age(30)4 .department("Engineering")5 .build();6
7System.out.println(emp);Each setter method in the Builder returns this (the builder object itself), enabling method chaining. Only build() returns the final Employee object.
Sequence Diagram
Immutability with `@Builder`
When you use @Builder without @Setter, the resulting object has no setter methods — it can only be constructed through the builder. After build() is called, the object's state cannot change.
1Employee emp = Employee.builder().name("Alice").build();2// emp.setName("Bob"); ❌ No setName() method exists!@Builder with @Value for a fully immutable object with a convenient builder API. This is a very common pattern in production Java code.12. Feature 10 `@Cleanup`
Overview
@Cleanup ensures that a resource (like an input/output stream, database connection, etc.) is automatically closed when the current code block exits — whether normally or due to an exception.
Why This Exists
Java requires resources like streams, connections, and readers to be explicitly closed. Without cleanup:
1FileInputStream fis = new FileInputStream("data.txt");2// If an exception happens here, fis is never closed → resource leak!3int data = fis.read();4fis.close(); // May never be reachedYou should always use a try-finally block:
1FileInputStream fis = null;2try {3 fis = new FileInputStream("data.txt");4 int data = fis.read();5} finally {6 if (fis != null) fis.close();7}This is verbose. Java 7 introduced try-with-resources, but @Cleanup is an alternative that keeps code even simpler.
Definition
@Cleanupgenerates atry-finallyblock around the annotated resource, ensuring itsclose()method is called before the execution path exits the current scope.
Syntax
1import lombok.Cleanup;2import java.io.*;3
4public class FileReader {5 public void readFile() throws IOException {6 @Cleanup FileInputStream fis = new FileInputStream("data.txt");7 // Use fis here — Lombok guarantees it will be closed8 int data = fis.read();9 System.out.println(data);10 } // fis.close() is called here automatically11}What Lombok Generates (Compiled `.class`)
1public void readFile() throws IOException {2 FileInputStream fis = new FileInputStream("data.txt");3 try {4 int data = fis.read();5 System.out.println(data);6 } finally {7 if (fis != null) {8 fis.close();9 }10 }11}Lombok wraps the usage of fis in a try-finally and calls .close() in the finally block.
Comparison with `try-with-resources`
| Feature | @Cleanup | try-with-resources |
|---|---|---|
| Java version | Java 6+ | Java 7+ |
| Syntax overhead | Very low | Low |
| Multiple resources | Stack annotations | Nest try or comma-separate |
| Standard Java | No (Lombok required) | Yes (standard Java) |
| IDE support without plugin | Poor | Full |
try-with-resources is the standard idiomatic approach. @Cleanup is a Lombok alternative that achieves the same result with slightly less syntax, but requires Lombok as a dependency.13. Quick Reference Table
| Annotation | What It Does |
|---|---|
val | Final local variable with inferred type |
var | Mutable local variable with inferred type |
@NonNull | Generates null check; throws NPE if null |
@Getter | Generates getXxx() / isXxx() method |
@Setter | Generates setXxx() method |
@ToString | Generates toString() method |
@NoArgsConstructor | Generates no-argument constructor |
@AllArgsConstructor | Generates constructor with all fields |
@RequiredArgsConstructor | Generates constructor for final and @NonNull fields |
@EqualsAndHashCode | Generates equals() and hashCode() |
@Data | @ToString + @EqualsAndHashCode + @Getter + @Setter (non-final) + @RequiredArgsConstructor |
@Value | Immutable @Data — all fields private final, class final, no setters |
@Builder | Generates Builder pattern inner class |
@Cleanup | Auto-closes resource via try-finally |
14. Interview Notes
Q1: What is Lombok and how does it work?
Answer: Lombok is a Java annotation-processing library that reduces boilerplate code. It works at compile time: the Lombok processor reads annotations on your source code and injects generated methods (getters, setters, constructors, etc.) directly into the AST (Abstract Syntax Tree). The resulting .class file contains all the generated code, but your .java source remains clean. There is no runtime dependency required.
Q2: What is the difference between `val` and `var` in Lombok?
Answer: Both infer the type from the initializer expression. val makes the variable final (immutable); var does not. Both only work for local variables, not fields or method parameters.
Q3: What does `@NonNull` generate and where can it be used?
Answer: @NonNull generates a null check (if (param == null) throw new NullPointerException(...)) as the first statement in the method or constructor. It can be used on method parameters, constructor parameters, and fields (the null check appears in the constructor when combined with @RequiredArgsConstructor or @AllArgsConstructor).
Q4: When using `@Setter` at the class level, which fields get a setter?
Answer: Only non-static, non-final fields get setters. Static fields are excluded because setters are instance-level operations. Final fields are excluded because their value cannot be reassigned after initialization.
Q5: What is the difference between `@Data` and `@Value`?
Answer: @Data generates a mutable POJO (fields are not final, setters are generated for non-final fields). @Value generates an immutable class (all fields are made private final, the class itself is made final, and no setters are generated).
Q6: Why does `@Value` generate `@AllArgsConstructor` while `@Data` generates `@RequiredArgsConstructor`?
Answer: @Data uses @RequiredArgsConstructor because fields can be mutable — you might set optional fields via setters after construction. @Value makes all fields final, so they must all be initialized in the constructor, which is equivalent to @AllArgsConstructor.
Q7: What does the `@Builder` annotation generate?
Answer: It generates an inner static Builder class with: one setter method per field (returning this for chaining), a static builder() factory method on the outer class, and a build() method that constructs the final object. The builder enables part-by-part object construction and can help achieve immutability.
Q8: What is the difference between `@Cleanup` and `try-with-resources`?
Answer: Both ensure resources are closed. @Cleanup is a Lombok annotation that generates try-finally. try-with-resources is standard Java (Java 7+) syntax that also generates cleanup code. try-with-resources is preferred in modern Java as it's a language feature with full IDE support and no external library needed.
Q9: Why does my IDE show compilation errors with Lombok even though the code compiles?
Answer: The IDE's real-time analysis runs before Lombok's annotation processor. Without the Lombok IDE plugin and annotation processing enabled, the IDE doesn't know what code Lombok will generate. After installing the plugin and enabling annotation processing in settings, the IDE becomes "Lombok-aware" and resolves the false errors.
Q10: Is Lombok a runtime dependency?
Answer: No. Lombok is a compile-time tool. The code it generates is written into .class files during compilation. At runtime, the generated bytecode runs without any knowledge of Lombok. The dependency can be set to in Maven.
15. Common Mistakes
val or var on a field (not a local variable)1// ❌ Wrong — val/var cannot be used as field types2public class Example {3 val name = "Hello"; // Compile error4}5
6// ✅ Correct — val/var only inside method bodies7public void method() {8 val name = "Hello"; // Works fine9}final field when using @Data or @Setter at class level1@Data2public class Config {3 private final String host = "localhost"; // final — NO setter generated!4}5
6// ✅ Remember: @Data setters are only generated for non-final fields@Data on a subclass may produce incorrect equals()1@Data2class Animal { private String name; }3
4@Data5class Dog extends Animal { private String breed; }6
7// equals() in Dog may not behave correctly for subclass equality8// ✅ Use @EqualsAndHashCode(callSuper = true) on the subclassWithout enabling annotation processing, Lombok-generated methods aren't visible to the IDE. You'll see red lines everywhere and missing method errors in code that actually compiles and runs fine. Always enable annotation processing alongside the Lombok plugin.
16. Best Practices
- Always use
for the Lombok Maven dependency — it's compile-time only.provided
- Use
@Datafor simple mutable POJOs — it bundles everything you typically need.
- Use
@Valuefor immutable value objects — DTOs, configuration, results.
- Use
@Builderwhen constructing objects with many optional fields — avoids telescoping constructors.
- Be careful with
@Datain inheritance — use@EqualsAndHashCode(callSuper = true)explicitly on subclasses.
- Prefer
@NonNullon parameters over inline null checks — it's self-documenting and consistent.
- Use
@ToString.Excludeto prevent sensitive fields (passwords, tokens) from appearing in logs.
- Commit the Lombok plugin settings to version control (
.ideafolder or equivalent) so all team members get the same IDE setup.
- Don't mix Lombok and manual implementations of the same method (e.g., don't use
@Getterand also write agetName()by hand — they'll conflict).
- Use
@Cleanuponly if you need Java 6 compatibility; prefertry-with-resourcesin Java 7+ projects.
17. Practice Questions
Easy
- What does
valdo differently fromvarin Lombok? - Which fields does
@Setterat class level skip? - What is the default access level of Lombok-generated getters and setters?
- What annotation would you use to suppress getter generation for a specific field when using
@Getterat class level? - What methods does
@Datagenerate?
Medium
- Write a class using
@Builderfor aProductwith fields:String name,double price,int stock. Show how to create an object using the builder. - Explain why
@Valuegenerates an@AllArgsConstructorwhile@Datagenerates a@RequiredArgsConstructor. - You have a class with a
passwordfield. You're using@ToStringat class level. How do you prevent the password from appearing in logs? - What happens when you put
@NonNullon a field and use@AllArgsConstructor? - Compare
@Cleanupand Java'stry-with-resources— when would you prefer each?
Hard
- A
Studentclass extendsPerson. Both use@Data. Explain what problem might arise withequals()and how to fix it. - Implement an immutable
Addressclass using@Valueand aPersonclass using@Builderthat contains anAddress. Show object creation. - Why is Lombok's
@NonNullcheck inserted before other code in the method body? What are the implications for debugging? - Explain how Lombok works at the JVM/compiler level. Why doesn't it modify your
.javasource files? - You have a class with 10 fields. 3 are
final, 2 are@NonNull, and 5 are optional. Which constructor annotations would you use and why?
18. Summary
Quick Revision Bullets
- Lombok reduces boilerplate by injecting code at compile time via annotation processing
val= final local variable with inferred type;var= mutable local variable with inferred type; both only work for local variables@NonNullgenerates a null check that throwsNullPointerExceptionif the parameter is null@Getter/@Settergenerate accessor methods; default access ispublic; useAccessLevel.NONEto suppress@ToStringgeneratestoString(); use@ToString.Excludeto hide fields;includeFieldNames=falseto hide field names@EqualsAndHashCodegenerates both methods following the equals-hashCode contract; excludes static and transient fields by default@Data=@ToString+@EqualsAndHashCode+@Getter(all) +@Setter(non-final) +@RequiredArgsConstructor@Value= immutable@Data; all fields becomeprivate final; class becomesfinal; no setters; uses@AllArgsConstructor@Buildergenerates an inner Builder class enabling fluent, part-by-part object construction with method chaining@Cleanupgeneratestry-finallyblock to close resources automatically- IDE Setup: Install Lombok plugin + enable Annotation Processing for full IDE support
- Maven: Use
— Lombok is compile-time only, no runtime dependency neededprovided
This guide covers the top 10 Lombok features most frequently encountered in Java production codebases. For the complete list of Lombok features, visit projectlombok.org.
Mastery check
How well can you recall this?
Finished this lesson?