I got an example to override the toString() method.
import java.util.Scanner;
public class Demo{
String name = "";
String age = "";
Demo(String name, String age){
this.name = name;
this.age = age;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the name:");
String name = scanner.next();
System.out.print("Enter the age:");
String age = scanner.next();
Demo test = new Demo(name, age);
System.out.println(test);
}
public String toString() {
return ("Name=>" + name + " and " + "Age=>" + age);
}
}
My doubt is, how is it printing test as Name=>abc and Age=>12 even when toString() method is not being called neither from constructor nor from main?
You're calling System.out.println(test)
, which is a call to PrintStream.println(Object)
. That will call toString()
on the reference you pass in, via String.valueOf
:
Prints an Object and then terminate the line. This method calls at first
String.valueOf(x)
to get the printed object's string value, then behaves as though it invokesprint(String)
and thenprintln()
.
See more on this question at Stackoverflow