This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString method

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • 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
 
Jimi Svedenholm
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • 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".
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic