aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toString() method" Watch "toString() method" New topic
Author

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() {
System.out.println("###");
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.
Luk
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12806
    
    5
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.
Bill

------------------
author of:
ryan burgdorfer
Ranch Hand

Joined: Jan 24, 2001
Posts: 219
So in the above code, will the output be
AAA###
or
AAAZ
or
AAA###Z
?


<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:
###
AAAZ
Note: seperate lines due to the println statement in the toString() method.
 
 
subject: toString() method