How to Override tostring() method in Java?The toString() function of any Java object returns a string representation of the object. By default, this function produces a string that contains the class name of the object, a "@" sign, and its hexadecimal hash code. However, there are situations when you would want to provide the object a more useful string representation. Why Override the toString() Method?The toString() function of any Java object returns a string representation of the object. This method typically produces a string that includes the class name of the object, a "@" sign, and the hash code of the object in hexadecimal format. This default representation, meanwhile, might not always be helpful. Consider a Person class, for instance, which has the fields name and age. The toString() method's default output looks like this if you try to print an instance of this class: It's difficult to determine what the object represents because this string doesn't provide any information about the person's name or age. One can override the toString() method & define a custom string representation to give the Person object a more meaningful representation. Best Practices for Overriding the toString() MethodHere are some best practices to keep in mind when overriding the toString() method in Java:
We can make meaningful and reliable string representations of your objects in Java by adhering to certain best practises. Here's the full Person class with the overridden toString() method: Person.java Output: Person{name='Alice', age=25} Using the toString() function that we've overridden in the Person class, we've produced a Person object in this example with the name "Alice" and the age 25. The toString() method's custom string representation for the Person object is displayed in the output. Overriding the toString() method in Java is a simple but powerful way to provide a meaningful string representation of your objects. By following the best practices outlined in in this section, we had generated consistent string representations that are easy to read and comprehend in the code. Recall to adopt a consistent format, be cautious with complex objects, and remember to include all pertinent information in the string representation. These principles will help you develop a toString() method that accurately and succinctly represents your objects. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India