English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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:
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().