Java program to print object of a class
www.iitfigdea.com
Here's a simple Java program to print an object of a class:
public class PrintObjectExample { public static void main(String[] args) { Person person = new Person("John", 30); System.out.println(person); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + '}'; } }
In this program, we have a Person
class with a name and age field. We create a Person
object with some values and print it to the console using the println()
method of System.out
. We have also overridden the toString()
method in the Person
class to print the object in a formatted string.
Output:
Person{name='John', age=30}
This program creates a Person
object, prints it to the console, and uses the overridden toString()
method to format the output. If you want to print other types of objects, you can modify the toString()
method to format the output accordingly.