File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "ToString method" Watch "ToString method" New topic
Author

ToString method

sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
HI All

Can any one please tell me what is the use of a toString menthod

With an example

Thanks
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

When you try to access the value of an Object (reference variable) like this

System.out.println(obj);
OR
String s = "Hello"+obj;

Then the compiler calls the toString() method on that object. So after compilation you code would look like-
System.out.println(obj.toString());
OR
String s = "hello"+obj.toString();

As a developer your job is to provide a toString method with your class and return the relevant details about the object as a String from the toString method.

Eg.


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: ToString method