JavaRush /Java Blog /Random EN /10 Tips for Overriding Java's toString() Method (Part 1)
Ku6ep
Level 35

10 Tips for Overriding Java's toString() Method (Part 1)

Published in the Random EN group
10 tips for overriding the toString() method in Java - ToStringBuilder Netbeans Eclipse 10 Tips for Overriding the toString() Method in Java (Part 1) - 1

Java toString method

toStringmethod in Java is used to provide clear and sufficient information about an object ( Object) in a human readable way. Proper method overriding toStringcan help with logging and debugging a Java program by providing valuable and important information. Since toString()it is defined in java.lang.Objectthe 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, Tradeor Employee, always override the equals , hashCode , compareTo , and toStringmethods in Java. Default implementationtoStringproduces output like package.class@hashCode, for our example toString(), toString()the class method Countrywill 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 Socketreal ServerSocketproblem toString, but with overridden implementationtoStringthey can provide useful information such as hostname and port number. In this Java tutorial, we will give some tips on method overriding toStringwith 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 method toString. The regular toString()class java.util.Datedoes 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 Dateand 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 Datein Java. You can also use the SimpleDataFormat class or the Joda Date time library for this.

Documentation of the toString format

If your method toString()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 method toString()in Java then use StringBuilder to add individual attributes. If you are using an IDE like Eclipse , Netbeans or IntelliJ then using StringBuilderthe and method append()instead of the + operator to compose toStringis also the right way to go. By default, both Eclipse and Netbeans generate toStringwith the concatenation operator.

Using the @Override annotation

Using @Overridemethod 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 method toStringand 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 Collectionsuch as ArrayListor HashSet instead Arrayfor storing other objects.

Bonus Tips

A few more bonus tips on overriding a method toStringin Java.
  1. Print output toStringin multiple lines or one line based on its length.

  2. Include full class names in the view toString, in other words package.classto avoid any misunderstanding.

  3. 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 nullat the time of an incident, such as a NullPointerException .

  4. Use a key-value format like , member.name=member.valuemost IDEs support this.

  5. Include inherited members if you think they should provide the necessary information to the derived class.

  6. 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.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION