• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

toString method

 
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello

Returns a string representation of the object.



http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#toString()


Can't we write our own method to return a string?If it is all about return a string....

May someone explain more about this:

a string representation of the object
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

abalfazl hossein wrote:
Can't we write our own method to return a string?If it is all about return a string....



Yes, you can most definitely write your own toString method for your own objects. If you haven't tried to do that yet then I suggest that you do. If you have any problems then you can post your code here and maybe someone can point out the error in your code.


May someone explain more about this:

a string representation of the object



Well, that is really only the short description. If you click the link "toString()" you will see the longer description. In short, this method should return a String that represents this object. For example, if the object is an instance of a class named Person, then to toString() method could return a String containing the persons name, phone number etc. Like: "John Doe, 1-23-456-789".
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

abalfazl hossein wrote:
Can't we write our own method to return a string?If it is all about return a string....


You can write as many methods as you want that return strings. toString() is special, though, because it's called automatically in certain circumstances where the Object is converted to a String.

For example, if anObject is any object you like:

is equivalent to

Because of this, it's a good idea to provide your own implementation of toString() whenever there's a sensible way to do it that's more appropriate than the built-in version.
 
reply
    Bookmark Topic Watch Topic
  • New Topic