Java toString() method

toString() method of the Object class is used to provide a string representation of an object.

When an object is passed in the print() method as an argument then the compiler internally calls the toString() method on the object. It returns object representation as classname@hexadecimal representation of the hash code of the object.

class Student{
    String name;
    String rollNo;
    
    //constructor
    Student(String name, String rollNo){
        this.name = name;
        this.rollNo = rollNo;
    }
}

public class ToStringExample1 {
    public static void main(String args[]){
        //creating Student class object
        Student stu1 = new Student("Roy", "MCA/07/15");
        Student stu2 = new Student("Alex", "MCA/07/19");
        Student stu3 = new Student("Root", "MCA/07/32");
        
        //println internally call toString method
        System.out.println(stu1);
        System.out.println(stu2);
        System.out.println(stu3);
    }
}

Output

com.w3schools.business.Student@1888759 
com.w3schools.business.Student@6e1408 
com.w3schools.business.Student@e53108

Note: We can override the toString() method for customized results.

class Student{
    String name;
    String rollNo;
    
    //constructor
    Student(String name, String rollNo){
        this.name = name;
        this.rollNo = rollNo;
    }
    
    //Override toString method to get customize results.
    public String toString(){
        return "Name:" + name + ", RollNo: " + rollNo;
    }
}

public class ToStringExample2 {
    public static void main(String args[]){
        //creating Student class object
        Student stu1 = new Student("Roy", "MCA/07/15");
        Student stu2 = new Student("Alex", "MCA/07/19");
        Student stu3 = new Student("Root", "MCA/07/32");
        
        //println internally call toString method
        System.out.println(stu1);
        System.out.println(stu2);
        System.out.println(stu3);
    }
}

Output

Name:Roy, RollNo: MCA/07/15 
Name:Alex, RollNo: MCA/07/19 
Name:Root, RollNo: MCA/07/32