This post is similar to Overriding equals method in Java. Consider the following Java program:
The output is, class name, then ‘at’ sign, and at the end hashCode of object. All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this). The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. For example, in the following code toString() is overridden to print “Real + i Imag” form.
10.0 + i15.0
In general, it is a good idea to override toString() as we get get proper output when an object is used in print() or println().
Effective Java by Joshua Bloch
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Overriding in Java
- Overriding equals method in Java
- Overriding methods from different packages in Java
- Exception Handling with Method Overriding in Java
- Java.lang.Short toString() method in Java with Examples
- Integer toString() in Java
- Arrays.toString() in Java with Examples
- CopyOnWriteArrayList toString() method in Java
- ThaiBuddhistDate toString() method in Java with Example
- JapaneseDate toString() method in Java with Example
- PriorityBlockingQueue toString() method in Java
- Object toString() Method in Java
- LinkedBlockingDeque toString() method in Java
- LinkedBlockingQueue toString() method in Java
- BigInteger toString() Method in Java
- StringJoiner toString() method in Java
- HijrahDate toString() method in Java with Example
- AbstractSequentialList toString() method in Java with Example
- FieldPosition toString() method in Java with Example
- LinkedHashSet toString() method in Java with Example