Java toString method
toString method in Java is used to provide clear and concise information about Object in human readable format. Correctly overridden toString method can help in loggingand debugging of Java program by providing valuable and meaningful information. Since toString() is defined in java.lang.Object class and its default implementation doesn't provide much information, its always a best practice to override toString method in sub class. In fact if you are creating value class or domain class e.g. Order, Trade or Employee, always override equals, ,hashCode, compareToand toString method in Java. By default toStringimplementation produce output in the form package.class@hashCode e.g. for our toString() example, Country class’ toString() method will print test.Country@18e2b22 where 18e2b22 is hashCode of object in hex format, if you call hashCode method it will return 26094370, which is decimal equivalent of 18e2b22. This information is not very useful while troubleshooting any problem. Let’s see a real life example where you are troubleshooting network connectivity issues, in case of this you want to know which host and port your system is trying to connect and if Socket or ServerSocket class only print default toString information than its impossible to figure out the actual problem, but with a decent toStringimplementation they can print useful information like hostname and port. In this Java tutorial we will see some tips to override toString method with code examples.