Which method is called when an object is printed with System.out.println?

The story behind the answer

The method called when an object is printed with System.out.println is toString(). Java uses this method to obtain the object's text representation.

Every Java class inherits toString() from java.lang.Object. Unless a class overrides it, the inherited version usually returns the class name followed by an at-sign and a hash-based value, such as Example@1a2b3c. Well-designed classes commonly override toString() to provide readable details.

System.out.println(Object) effectively converts its argument to text before writing it. For a non-null object, that conversion invokes toString(); for a null reference, Java prints the word "null" instead. This is why println(obj) and println(obj.toString()) often appear to produce the same output, although explicitly calling toString() on null would throw a NullPointerException.

A common mix-up is hashCode(), which supports hashing and collections rather than display. valueOf() is associated with conversion methods such as String.valueOf(), while print() is not the object-conversion hook used here.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: