English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Other Java topics

Java program to print the object of a class

Comprehensive Java Examples

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

To understand this example, you should understand the followingJava programmingTopic:

Example1: Java program to print objects

class Test {
}
class Main {
  public static void main(String[] args) {
    // Create an Object of Test Class
    Test obj = new Test();
    //Print Object
    System.out.println(obj);
  }
}

Output Result

Test@512ddf17

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

This is because when printing an object, the toString() method of the object's class is called. It formats the object in the default format. As shown below:

  • Test - Class Name

  • @ - Concatenate Strings

  • 512ddf17 - Object Hash Code

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

class Test {
  @Override
  public String toString() {
    return "object";
  }
}
class Main {
  public static void main(String[] args) {
    //Create an Object of Test Class
    Test obj = new Test();
    // Print Object
    System.out.println(obj);
  }
}

Output Result

object

In the above example, the output has changed. This is because here we have overridden the method toString() that returns a string from the object.

To understand the method toString() of the Object class, please visitJava Object toString().

Comprehensive Java Examples