Why implement your own toString method?

In this post I show You why it is worth to implement own toString method.

Create in Netbeans IDE project of MyStringObject name.

In tree project You see MyStringObject file with its main method.

MyStringObject class is empty class.

Create another class of Student name. Right click on package with main class and choose from menu New-> Java Class.

In Class Name field write Student and click on Finish button.

In tree of project You see file with new class.

The Student class is empty.

Paste into  Student.java class this code:

package mystringobject;

public class Student
{
    private String firstname;
    private String surname;
    private int age;
    
     public Student(String firstname,String surname, int age)
     {
       this.firstname = firstname;
       this.surname = surname;
       this.age = age;
     }
     
    public void setFirstname(String firstname)
    {
        this.firstname = firstname;
    }
    public void setSurname(String surname)
    {
        this.surname = surname;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    
    public String getFirstname()
    {
        return firstname;
    }    
    public String getSurname()
    {
        return surname;
    }
    public int getAge()
    {
        return age;
    }  
}

Then in main method of MyStringObject class paste this code:

       Student harry = new Student("Harry","Smith",23);
       Student kate = new Student("Kate","Muller",20);       
       System.out.println(""+harry.toString());
       System.out.println(""+kate.toString());

Run your application. You see name of package, name of class and hashcode.

If you add in Student class new method( toString ), You may fit it. Add this code into Student.java file:

public String toString()
    {
    return "Student object: "+getFirstname()+" "+getSurname()+", "+getAge();
    }

If you run application, You see information about data of objects.