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

using toString()

 
billo bailey
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
heres a pretty basic question but it has been confusing me. I assumed when i saw the toString method i could pass it an integer and it would give me a string but i haven't been getting it right. i've been trying

can someone set me striaght with a simple example of how this method works.
i thank you
 
Ta Ri Ki Sun
Ranch Hand
Posts: 442
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
from the API
String toString()
This object (which is already a string!) is itself returned.

also from String API
Overrides:
toString in class Object

from that I'm sure you can tell your own Objects can override the toString method in every class's daddy , Object, if you need a String representation of your own Object.
now in order to get a String representing the int you speak of try this.
static String valueOf(int i)
Returns the string representation of the int argument.

check the API theres a valueOf method for other primitives as well, and also one that takes an Object
 
Francis Siu
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi billo
Compile you code giving me error as following

1: not an expression statement at (a)
variable new can not use because it is reserve word.
2: method toString(int) not found (a)
3: object type required.int is primitive type so you can not use it call toString method
I hope that I can answer your question
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exercise left for the students
 
Francis Siu
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oo..
Exercise left for the students

A good exercise that needed to use the compiler that I never use it to test something
Now I must use it whatever I test
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, you can't use "new" as a variable name since it is a keyword. Second of all, int is primitive type and not an Object, so you can't call toString() on a variable with type int.
With that said, you can use the Integer class to get the String representation of the int variable. You should become intimately familiar with
the API docs so you can look up such information in the future.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic