toString Java Method: How to Make Your Life Easier

toString method in JavaJava Object toString method is one of the basics in Java.

toString function returns a string representation of an object.

I’ll explain how to add toString method to a Java class with code examples.

Using toString in Java

To string method in Java should be informative to make it easy to read.

it’s recommended to override this method in each class.

By default Java object toString method implementation looks like this:

For example, you have a Car class:

The output of default toString method will be the following:

It’s not human readable.

That’s why we need to override it.

I’ll provide you 3 ways how to do it without any problems.

Generate toString using Intellij IDEA

There is “Generate” option in the main menu.

Generate menu in Intellij

It proposes you to generate few boilerplate things like a toString() method:

Generate toString method using Intellij

Select toString method and choose class fields to use:

Select fields for toString method in Intellij

The result is:

If you’ll print a car object like this:

Output:

The result is good, but it’s not convenient to change toString method every time when you want to add a new class field.

ToStringBuilder from apache.commons

If you want to print all fields every time and don’t want to change toString method every time – ToStringBuilder is a good choice.

First of all, you need to add maven dependency to the commons-lang3 library:

ToString method looks like this:

Output:

As you can see 2nd parameter is a style.

There are 7 options, so you’ll definitely find a good style for you.

Lombok @ToString

It’s my favorite way to make toString method in Java.

Lombok is awesome production-ready Java library to generate your boilerplate code.

Installation guide is here.

Example:

Looks better? No, looks excellent!

Output:

As you can see Lombok can generate constructors as well and more “tasty” things.

You should at least take a look at its features.

Java Array ToString Method

If you’ll try to print an array like this:

You’ll get a little bit, not human-readable output:

The first idea is to iterate through the array and print each element like this:

But there is a better solution in Java:

Output:

Conclusion

ToString method in Java looks easy, but there are many ways how to make your life easier and generate boilerplate code.

Don’t afraid to use Lombok, it’s awesome.

Please, ask questions.

 

Scroll Up