Java Object toString() Method Example

In this example, we will demonstrate the usage of java.lang.Object.toString() method with an example.

The java.lang.Object.toString() method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Object toString() Method Example

The following example shows the usage of lang.Object.toString() method.
public class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
       return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    public static void main(String[] args) {
        Person person = new Person();
Let us compile and run the above program, this will produce the following result −
Person [firstName=Ramesh, lastName=Fadatare]


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course