Home » Understanding toString() method

Understanding toString() method

by Online Tutorials Library

Java toString() Method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the String representation of the object.

If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don’t need to write much code.

Understanding problem without toString() method

Let’s see the simple code that prints reference.

Student.java

Output:

As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since Java compiler internally calls toString() method, overriding this method will return the specified values. Let’s understand it with the example given below:

Example of Java toString() method

Let’s see an example of toString() method.

Student.java

Output:

101 Raj lucknow  102 Vijay ghaziabad  

In the above program, Java compiler internally calls toString() method, overriding this method will return the specified values of s1 and s2 objects of Student class.


You may also like