Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


Change the order of fields in the @ToString annotation in Java



The @ToString annotation is one of the annotations in the project Lombok.

Note: Refer What is the @ToString annotation in Lombok? for the introduction of the annotation.

The @ToString annotation generates an implementation for the toString() method where the class name, along with each field in order, separated by commas, is printed. But sometimes, the ordering of the fields needs to be different in the string representation of the fields.

For example, consider a Person class with three attributes, name, age, and address:

class Person {
      private int age;
      private String name;
      private String address;

We define an instance of the Person class:

Person person = new Person(30, "sam", "US");

The default string representation of the above object is as follows:

Person(age=30, name=sam, address=US)

The ordering of the fields is the order defined in the class. If we want to print the name first, address second, and age last, we do as follows:

Person(name=sam, address=US, age=30)

rank parameter

The rank parameter of the Include interface of the ToString annotation is used to order the fields in the string representation. The higher the rank, the earlier it is printed. Fields with the same rank are printed in the order they appear in the source file.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""









  • Lines 1 and 2: We import the AllArgsConstructor and ToString annotations.

  • Lines 6 to 8: We define the Person class annotated with @AllArgsConstructor and @ToString annotations.

  • Lines 10 and 11: We define the age field with rank as 1.

  • Lines 13 and 14: We define the name field with rank as 2.

  • Lines 16 and 17: We define the address field with rank as 3.

  • Line 22: We create an instance of the Person class.

  • Line 23: We print the person instance created in Line 22 to console.

The address field has a higher rank. It is printed first, then name, and finally age.



View all Courses

Keep Exploring