Java toString method
toString
method in Java is used to provide clear and sufficient information about an object ( Object
) in a human-readable form. Proper method overriding toString
can help in logging and debugging a Java program by providing valuable and important information. Since toString()
it is defined in java.lang.Object
a 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 general class of type Order
, Trade
or Employee
, always override equals , hashCode , compareTo and toString
methods in Java. By default the implementation toString
produces output in the form , package.class@hashCode
for example for our example the class method will print test.Country@18e2b22 where 18e2b22 is the hash code of the object in hexadecimal, if you call the hashCode method it will return 260943370 which is the decimal equivalent of 18e2b22. This information is not particularly useful when searching for a problem. Let's look at a real life example where you need to find a problem in your network connection, in the event that you want to know which host and port your system is trying to connect to and if or only prints the default information, it will be impossible to imagine the real problem, but with an overridden implementation they can provide useful information such as hostname and port number. In this Java tutorial we will give some tips on method overriding with code examples. toString()
toString()
Country
Socket
ServerSocket
toString
toString
toString
How to override toString method in Java:
Prints the formatted date (i.e. day/month/year) instead of the 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 a lot of details that are not always needed. If you are using partial DateFormat i.e. dd-MM-yy in your application, then you would definitely want to see this format instead of the default one. The IDE usually doesn't generate formatted output Date
and this is something you'll 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.
Documenting the toString format
If your methodtoString()
does not output data as 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 a good practice would be to specify the format as "name-id-department-contact", but at the same time do not allow the client to get information from the method toString()
, you should always provide appropriate methods for retrieving data, such as getName()
, getId()
, getContact()
and so on, since the information obtained from toString()
the object representation is fragile and error-prone, so the client should always have a clean path to obtain 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 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 in the case of overriding the equals()
and methods compareTo()
, since overloading instead of overriding can create more subtle errors that are difficult to calculate. In any case, it is better to use the annotation @Overrride
.
Printing the contents of an array instead of printing the 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 look at whether printing the contents of an 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 ArrayList
or HashSet instead Array
to store other objects.
Bonus tips
Some more bonus tips on method overridingtoString
in Java.
-
Print output
toString
in multiple lines or in one based on its length. -
Include fully qualified class names in the representation
toString
, in other wordspackage.class
to avoid any misunderstanding. -
You can skip null values or show them, but it's better to show them. Sometimes they are useful because they show which field is present
null
during some incident, for example NullPointerException . -
Use a key-value format, for example
member.name=member.value
, most IDEs support this. -
Include inherited members if you think they should provide necessary information to the inheriting 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 we can print only the required fields, especially since we have optional ones.
GO TO FULL VERSION