Join our newsletter for the latest updates.
Java Program to Print object of a class

Java Program to Print object of a class

In this tutorial, we will learn to print the object of a class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to print the object

class Test {

}

class Main {
  public static void main(String[] args) {

    // create an object of the Test class
    Test obj = new Test();

    // print the object
    System.out.println(obj);
  }
}

Output

Test@512ddf17

In the above example, we have created an object of the class Test. When we print the object, we can see that the output looks different.

This is because while printing the object, the toString() method of the object class is called. It formats the object in the default format. That is,

  • Test - name of the class
  • @ - joins the string
  • 512ddf17 - hashcode value of the object

If we want to format the output in our own way, we need to override the toString() method inside the class. For example,

class Test {

  @Override
  public String toString() {
    return "object";
  }
}

class Main {
  public static void main(String[] args) {

    // create an object of the Test class
    Test obj = new Test();

    // print the object
    System.out.println(obj);
  }
}

Output

object

In the above example, the output has changed. It is because here we override the toString() method to return the string object.

To learn about toString() method of the object class, visit Java Object toString().