learn java
The moose likes Beginning Java and the fly likes How this print() method works? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How this print() method works?" Watch "How this print() method works?" New topic

How this print() method works?

Debapriya Mukherjee

Joined: Mar 07, 2012
Posts: 4
When I am Trying to Print an Object

It gives me
This seems to be a output of toString() method.
How this internal call happening?
I tried seeing the class hierarchy but getting confused?

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14667

This is how you find out:

- Look at the API documentation of class java.lang.System
- You see that it has a static member variable called "out", which is a java.io.PrintStream
- Look at the API documentation of class java.io.PrintStream
- You see that it has several overloaded versions of the print(...) method
- For your A object, it uses the print(Object) version
- Look at the API documentation for that method; it says:
API documentation wrote:Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

So now you know that it calls String.valueOf(...) with your object as the argument. The API documentation of String.valueOf(...) says:
API documentation wrote:Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

In other words, this calls toString() on your object.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 41599
Read about toString() here.
It is sorta covered in the JavaRanch Style Guide.
subject: How this print() method works?