Object toString() Method in Java
Last Updated :
04 Apr, 2025
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class, henceforth, it is a child of the Object class. If a class does not extend any other class then it is a direct child class of Object, and if it extends another class, then it is indirectly derived. Therefore the Object class methods are available to all Java classes.
Note: The Object class acts as the root of the inheritance hierarchy in any Java program.

Now we will be dealing with one of its methods, known as the toString() method. We typically do use the toString() method to get the string representation of an object. It is very important and readers should be aware that whenever we try to print the object reference, then internally toString() method is invoked. If we did not define the toString() method in our class, then the Object class toString() method is invoked; otherwise, our implemented or overridden toString() method will be called.
Syntax:
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
Note: Default behavior of toString() is to print class name, then @, then unsigned hexadecimal representation of the hash code of the object.
Example: Default behaviour of the object.toString() method.
JAVA
// Java program to Illustrate
// working of toString() method
public class Geeks
{
String name;
String age;
Geeks(String name, String age) {
this.name = name;
this.age = age;
}
// Main Method
public static void main(String[] args)
{
Geeks g1 = new Geeks("Geeks", "22");
// printing the hashcode of the objects
System.out.println(g1.toString());
}
}
Output explanation: In the above program, we create an Object of Geeks class and provide all the information of a friend. But when we try to print the Object, then we are getting some output which is in the form of classname@HashCode_in_Hexadeciaml_form. If we want the proper information about the Geeks object, then we have to override the toString() method of the Object class in our Geeks class.
Example 2: Overriding the toString() method to enhance the output formatting.
Java
// Java program to Illustrate
// working of toString() method
public class Geeks
{
String name;
String age;
Geeks(String name, String age) {
this.name = name;
this.age = age;
}
// Overriding toString() method
@Override
public String toString() {
return "Geeks object => {" +
"name='" + name + '\'' +
", age='" + age + '\''+
'}'
;
}
// Main Method
public static void main(String[] args)
{
Geeks g1 = new Geeks("Geeks", "22");
// printing the hashcode of the objects
System.out.println(g1.toString());
}
}
OutputGeeks object => {name='Geeks', age='22'}
Note: In all wrapper classes, all collection classes, String class, StringBuffer, StringBuilder classes toString() method is overridden for meaningful String representation. Hence, it is highly recommended to override toString() method in our class also.