This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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 REST with Spring (video course) this week in the Spring 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: 15045

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
- Look at the API documentation of class
- 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: 45348
Read about toString() here.
I agree. Here's the link:
subject: How this print() method works?
It's not a secret anymore!