# @ToString Lombok annotation

In 
Published 2022-12-03

The project Lombok is a popular Java library that is used to minimize/remove the boilerplate code.

For using Lombok, we need to add the Lombok dependency. My example is using Maven, so the dependency is the following:

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.26</version>
   <scope>provided</scope>
</dependency>

Also, my example is using Spring Boot, and it is created by using Spring Initializr.

The @ToString annotation is used when we want to print the variables of a class instance with less code/boilerplate.

Here are an example of using the @ToString annotation.

I will create two "Employee" classes and for one class I will use the @ToString annotation.

Employee.class
package com.example.employee;

import lombok.ToString;

@ToString
public class Employee {
    private String id;
    private String name;

    public Employee(String id, String name) {
        this.id = id;
        this.name = name;
    }
}
Employee2.class
package com.example.employee;

public class Employee2 {
    private String id;
    private String name;

    public Employee2(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

And here we can see how @ToString annotation is working:

SpringApplication.class
package com.example;

import com.example.employee.Employee;
import com.example.employee.Employee2;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringApplication {

	public static void main(String[] args) {
		org.springframework.boot.SpringApplication.run(SpringApplication.class, args);
		System.out.println("Here starts the Spring application !");

		Employee emp1 = new Employee("10", "John");
		Employee2 emp2 = new Employee2("11", "Anna");

		System.out.println("emp1/name="+emp1.toString());
		System.out.println("emp2/name="+emp2.toString());

		System.out.println("------    END   ------");
	}
}

When we run the code we can see:

Here starts Spring application !
emp1/name=Employee(id=10, name=John)
emp2/name=com.example.employee.Employee2@5db99216
------    END   ------

Process finished with exit code 0