toString( ) method is one of the Object Class methods. As all the Classes in Java are the sub classes of the Object Class, any Class can access this method.
toString( ) method is used to represent any object as a String. i.e. toString( ) method returns the String representation of the given object.
Syntax of toString( ) method -
object1.toString( ); //toString( ) method returns the String representation of the given object 'object1'
Lets Implement the toString( ) method on Eclipse IDE -
1. Launch Eclipse IDE, open the Java Project created in our previous post 'Project 34' for printing an object as shown below -
2. Use the toString( ) method with the object 'object1' in the another print statement as shown below -
3. Save and Run the Java Class file 'ClassXYZ' and view the output in the Eclipse IDE console as shown below -
Observe that the same output is displayed on printing an object with or without using toString( ) method above.
The reason behind this is when you write System.out.println(object) -> compiler reads it as object.toString( ) even though we have not mentioned the toString( ) method in the statement. Hence the following two statements are same -
As you can see, the above two statements are printing ClassName followed by the Hash code. But lets get the values of these objects by implementing a different program in the next post.
Please comment below to feedback or ask questions.