File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes using toString() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "using toString()" Watch "using toString()" New topic

using toString()

billo bailey
Ranch Hand

Joined: Dec 02, 2002
Posts: 50
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

only users lose drugs
Ta Ri Ki Sun
Ranch Hand

Joined: Mar 26, 2002
Posts: 442
from the API
String toString()
This object (which is already a string!) is itself returned.

also from String API
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

Joined: Jan 04, 2003
Posts: 867
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 is primitive type so you can not use it call toString method
I hope that I can answer your question

Francis Siu
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Exercise left for the students

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
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

Joined: Dec 06, 2001
Posts: 3061
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.

Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: using toString()
jQuery in Action, 3rd edition