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 how toString() works in this program??? 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 "how toString() works in this program???" Watch "how toString() works in this program???" New topic

how toString() works in this program???

Ranch Hand

Joined: Jun 16, 2004
Posts: 41
public class BobTest {
public static void main (String[] args) {
Bob f = new Bob("GoBobGo", 19);
class Bob {
int shoeSize;
String nickName;
Bob(String nickName, int shoeSize) {
this.shoeSize = shoeSize;
this.nickName = nickName;
public String toString() {
return ("I am a Bob, but you can call me " + nickName +
". My shoe size is " + shoeSize);


in our main method i have not called the toString() method . But itis called with out my knowledge and the message is printed as" i am bob but u can call mehashaa and my shoe size 5" it happens???
Fletcher Estes
Ranch Hand

Joined: Jul 01, 2004
Posts: 108
System.out.println() automatically calls the toString method on any object passed to it.
Vijayendra V Rao
Ranch Hand

Joined: Jul 04, 2004
Posts: 195
All classes automatically inherit the toString( ) method of the Object class. So, whenever you try to print out an object, the toString() method will be called by default. The only difference is, if you have overrided that method, then your custom toString() method will be called or else, the default toString() method of the super class, Object, will be called.

If you wish to know more about this toString( ) method, then you should surely read this.

Vijayendra <br /> <br />"The harder you train in peace, the lesser you bleed in war"
I agree. Here's the link:
subject: how toString() works in this program???
It's not a secret anymore!