File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes System.out.println(this)? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "System.out.println(this)?" Watch "System.out.println(this)?" New topic


Pui Shing Lee

Joined: Jul 23, 2005
Posts: 10

I compile and run, the output is:
In test

My question is what does "System.out.println(this);" do? Why it give trial42@107077e?
[ July 25, 2005: Message edited by: Barry Gaunt ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

println(Object) calls toString() on the argument; this String is then displayed. See the Javadocs for java.lang.Object.toString() (which your class inherits, because it doesn't override this method) for a detailed explanation.

[Jess in Action][AskingGoodQuestions]
Mohamed Shafi
Ranch Hand

Joined: Apr 18, 2005
Posts: 119
hi Pui Shing Lee,

this usually invokes the current reference when u try to print using the line


u r trying to print the object reference using toString(). check out the sample ...

class trial
public static void main(String args[])
trial obj=new trial();

u get output as trial@13e8d89

Hope this helps...



Regards,<br /> <br />Shafi.
lalit upadheyay
Ranch Hand

Joined: Jun 20, 2005
Posts: 110
what does "System.out.println(this);" do?

It implicitly invokes the toString() method for anything supplied to it as parameter ( whether primitive or object references ), here the current object reference . Since your class does not provide implementation of public String toString(Object o) method , it will inherit implemenattion from its parent class i.e. Object class, and will invoke it here.

Why it give trial42@107077e?
If your class does not override the implementation of toString() method inherited by your class from the Object class ( grand dady of all classes ) then you will get class name here trial42 followed by hashCode() for the object. For details regarding these methods i would suggest you to refer to API documentation for Object class

SCJP1.4, SCWCD1.4, SCBCD5.0(working on...)
I agree. Here's the link:
subject: System.out.println(this)?
It's not a secret anymore!