wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toString() method 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 "toString() method" Watch "toString() method" New topic

toString() method

luk Hann
Ranch Hand

Joined: Jan 29, 2001
Posts: 48
I don't quite understand how the following code works:
class Z {
public static void main(String[] args) {
System.out.println("AAA" + new Z());

public String toString() {
return "Z";
What on earth toString() method did here? Why new Z() will invoke this method? What is something special about toString() method? I am very confused about this method, pls clarify me. Thanks.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
When the compiler sees and expression such as
"AAA" + obj
where obj is any object reference, it automatically assumes that what is wanted is the String representation of obj - ie the result of obj.toString()
I generally try to give every class I create a toString method that tells something about the state of the object - very handy in debugging.

author of:
ryan burgdorfer
Ranch Hand

Joined: Jan 24, 2001
Posts: 219
So in the above code, will the output be

<UL TYPE=SQUARE><I><LI>Ryan Burgdorfer<BR><LI>Java Acolyte</I></UL>
Bob Young
Ranch Hand

Joined: Dec 23, 2000
Posts: 65
Output will be:
Note: seperate lines due to the println statement in the toString() method.
I agree. Here's the link: http://aspose.com/file-tools
subject: toString() method
It's not a secret anymore!