JavaRush /Java Blog /Random EN /10 Tips for Overriding the toString() Method in Java (Par...
Ku6ep
Level 35

10 Tips for Overriding the toString() Method in Java (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 form. Proper method overriding toStringcan help in logging and debugging a Java program by providing valuable and important information. Since toString()it is defined in java.lang.Objecta 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, Tradeor Employee, always override equals , hashCode , compareTo and toStringmethods in Java. By default the implementation toStringproduces output in the form , package.class@hashCodefor 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()CountrySocketServerSockettoStringtoStringtoString

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 method toString. The regular toString()class java.util.Datedoes 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 Dateand 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 Datein Java. You can also use the SimpleDataFormat class or the Joda Date time library for this.

Documenting the toString format

If your method toString()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 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 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 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 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 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 Collectionsuch ArrayListor HashSet instead Arrayto store other objects.

Bonus tips

Some more bonus tips on method overriding toStringin Java.
  1. Print output toStringin multiple lines or in one based on its length.

  2. Include fully qualified class names in the representation 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. Sometimes they are useful because they show which field is present nullduring some incident, for example NullPointerException .

  4. Use a key-value format, for example member.name=member.value, most IDEs support this.

  5. Include inherited members if you think they should provide necessary information to the inheriting 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 we can 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