Overriding toString() method
The toString() method is inherited by every class from the java.lang.Object class. Whenever an object reference is passed to the System.out.println() method, the object’s toString() method is called.
For example-
public class test { int x; public test(int x){ this.x=x; } public static void main(String args[]) { test obj = new test(2); System.out.println(obj); } }
Output-
test@33
The preceding is what you get when toString() method is not overridden. The output is the class name followed by the @ symbol, followed by the unsigned hexadecimal representation of the object’s hashcode. So the above output is not much of a help for a human. So to get a more meaningful information about the objects of a class, you need to override the toString() method.
Modified version of the previous class-
public class test { int x; public test(int x){ this.x=x; } public String toString(){ return "Hi this is test class and my x value is "+this.x; } public static void main(String args[]) { test obj = new test(2); System.out.println(obj); } }
Output-
Hi this is test class and my x value is 2