Why is the toString() method being called when I print an object?

On Refering to java docs what i undestand is that,

When you call PrintStream class print(obj) / println(obj) method then internally it called write method with arguement as String.valueOf(obj) shown below :

public void print(Object obj) {
    write(String.valueOf(obj));
}

Now String.valueOf(obj) does the task of calling to String method as shown below :

 /**
 * Returns the string representation of the <code>Object</code> argument.
 *
 * @param   obj   an <code>Object</code>.
 * @return  if the argument is <code>null</code>, then a string equal to
 *          <code>"null"</code>; otherwise, the value of
 *          <code>obj.toString()</code> is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

Leave a Comment