In Java, an object is an instance of a class.
It contains data and methods that define its behavior.
In this tutorial, we’ll discuss how to print an object of a class in Java.
To print an object of a class, we first need to create a class.
For this example, let’s create a simple class called “Person”.
The Person class will have two properties, “name” and “age”, and a constructor to initialize those properties.
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } }
Now that we have our class, we can create an object of it in our main method.
public static void main(String[] args) { Person person = new Person("John", 30); }
To print the object, we can simply use the System.out.println method and pass the object as an argument.
System.out.println(person);
However, if we try to print the object now, we’ll get a memory address instead of the values of the properties.
To print the values of the properties, we need to override the toString method of the Person class.
@Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; }
Now if we try to print the object again, we’ll get the values of the properties instead of the memory address.
Person person = new Person("John", 30); System.out.println(person); // prints "Person{name='John', age=30}"
In conclusion, to print an object of a class in Java, we need to create a class with properties and a constructor, create an object of the class, and override the toString method to print the values of the properties.