toString() Method in Java | How to Use toString in Java – Scaler Topics

The toString method is a method of the object class in java and it is inherited by all the classes in java by default. It provides the string representation of any object in java.

toString method in Java

The Object class is the parent of all the classes in Java. Hence, all the methods available in the Object class are available in all the Java classes by default. One of them is the toString() method. By using this method we can get the String representation of any object. The default implementation of the toString() method in the Object class looks like this (code snippet 1):

Code snippet 1:

public

String

toString

()

{

return

this

.getClass().getName() +

"@"

+ Integer.toHexString(

this

.hashCode());

}

Now let’s define a class Student with two member variables.

Code snippet 2:

class

Student

{

String name; Integer rollNo; }

and when we print the object of this class as

Code snippet 3:

public

class

Main

{

public

static

void

main

(String args[])

{

Student student =

new

Student();

student.name =

"Rohan"

;

student.rollNo =

34

;

System.out.println(student.toString()); } }

This program will print [email protected](the hexcode after ‘@’ can be different) to the console. Here our motive was to print a String representation of the object but, we didn’t get what we wanted. We expected that the name and rollNo will be printed. Since the default implementation of the toString() method (as shown in code snippet 1) is this.getClass().getName() + “@” + Integer.toHexString(this.hashCode()), it is not helping us in anyway other than printing the class name. So, here we need to override the existing toString() method and have our own implementation.

Note: Let’s not confuse this with inheritance . We don’t explicitly extend the Object class. This is the work of the Java compiler. The compiler checks for the method toString() and invokes whichever is required(default or overridden).

Let’s print the information of the student object in code snippet 3.