Java toString method
toString
method in Java is used to provide clear and sufficient information about an object ( Object
) in a human readable way. Proper method overriding toString
can help with logging and debugging a Java program by providing valuable and important information. Since toString()
it is defined in java.lang.Object
the class and its default implementation does not provide much information, it is always best practice to override this method in a descendant class. In fact, if you are creating an important or generic class like Order
, Trade
or Employee
, always override the equals , hashCode , compareTo , and toString
methods in Java. Default implementationtoString
produces output like package.class@hashCode
, for our example toString()
, toString()
the class method Country
will print test.Country@18e2b22 where 18e2b22 is the hashcode of the object in hex, if you call the hashCode method it will return 260943370 which is the decimal equivalent of 18e2b22. This information is not particularly useful when looking for a problem. Let's look at a real life example where you need to find a network connection problem, in case you want to know which host and port your system is trying to connect to and if either only prints the default information, then it will be impossible to imagine a Socket
real ServerSocket
problem toString
, but with overridden implementationtoString
they can provide useful information such as hostname and port number. In this Java tutorial, we will give some tips on method overriding toString
with code examples.
How to override the toString method in Java:
Print a formatted date (i.e. day/month/year) instead of a "raw" value. This is a very useful hint when overriding a Java methodtoString
. The regular toString()
class java.util.Date
does not output a formatted date and includes many details that are not always needed. If you are using a partial DateFormat i.e. dd-MM-yy in your application, then you would definitely like to see this format instead of the default. The IDE doesn't usually generate formatted output Date
and this is something you need to do yourself, but it's worth it. Read How to print Date in ddMMyy format in Java for details on formatting Date
in Java. You can also use the SimpleDataFormat class or the Joda Date time library for this.
Documentation of the toString format
If your methodtoString()
does not output in the form field=value, then it is a good idea to document the output format toString
, especially for important objects like Employee or Student. For example, if a toString()
class method Работник(Employee)
prints " John-101-Sales-9846387321 " then it's good practice to specify the format as "name-id-department-contact", but at the same time don't let the client get information from the method toString()
, you should always provide appropriate methods for retrieving data, such as getName()
, getId()
, getContact()
and so on, because the information retrieved from toString()
an object representation is fragile and error prone, so the client must always have a clean path to get the information.
Use StringBuilder to compose the output of toString()
If you are writing code for a methodtoString()
in Java then use StringBuilder to add individual attributes. If you are using an IDE like Eclipse , Netbeans or IntelliJ then using StringBuilder
the and method append()
instead of the + operator to compose toString
is also the right way to go. By default, both Eclipse and Netbeans generate toString
with the concatenation operator.
Using the @Override annotation
Using@Override
method overriding in Java is one of the best practices in the language. But this hint is not as important as it would be with method overriding equals()
and compareTo()
, since overloading instead of overriding can create more subtle, hard-to-calculate bugs. In any case, it's better to use the annotation @Overrride
.
Printing the contents of an array, instead of printing an array object
An array is an object in Java but it does not override a methodtoString
and when you print an array the default output format is not very useful as we would like to see the contents of the array. By the way, this is another reason why char[] array is preferable to String for storing sensitive data, such as a password. Take the time to see if printing the contents of the array helps your clients or not, and if it makes sense, then print the contents of the array instead of the object itself. For performance reasons it is preferable to use Collection
such as ArrayList
or HashSet instead Array
for storing other objects.
Bonus Tips
A few more bonus tips on overriding a methodtoString
in Java.
-
Print output
toString
in multiple lines or one line based on its length. -
Include full class names in the view
toString
, in other wordspackage.class
to avoid any misunderstanding. -
You can skip null values or show them, but it's better to show them. They are sometimes useful as they indicate which field is present
null
at the time of an incident, such as a NullPointerException . -
Use a key-value format like ,
member.name=member.value
most IDEs support this. -
Include inherited members if you think they should provide the necessary information to the derived class.
-
Sometimes an object contains many optional and required parameters, as we showed in our Builder template example , when it is almost impossible to print all the fields, in this case it is possible to print only the required fields, especially since we have optional ones.
GO TO FULL VERSION