Every Java beginners must know about toString() method of java.lang.Object class. As you know java.lang.Object is the super most class in Java. Every pre-defined and user-defined class can override the methods available in the class java.lang.Object.
Of these, toString() method plays a vital role. See the following example:
int x = 100;
System.out.println(x);
This will print 100. Discuss the below example too:
class Student{
private String name;
public Student(String studentName){ name=studentName; }
private void setName(String name){ this.name=name; }
private String getName(){ return name; }
}
class ABC{
public static void main(String [] a){
Student s=new Student("Guru");
System.out.println(s);
}
}
Can you guess the output of the above program? Dirtily, it prints the object reference, not some meaningful information (such as student name, in this example). Now see this example:
class Student{
private String name;
public Student(String studentName){ name=studentName; }
private void setName(String name){ this.name=name; }
private String getName(){ return name; }
/** method overridden **/
public String toString(){ return name; }
}
class ABC{
public static void main(String [] a){
Student s=new Student("Guru");
System.out.println(s);
}
}
This prints Guru. So, overriding toString() method improves your object quality and very very helpful when you directly pass or print object.