Valhalla Legends Forums Archive | Java Programming | conversion of object to string

AuthorMessageTime
touchstone
hi, i have a question on the following...

suppose, i have a class

class sample
{
int x;
float y;
String s;

sample(int par1,float par2,String par3)
{
x =par1;
y = par2;
s = par3;
}

}

now i am creating an object...

sample p = new sample(12,45.60,"test");


my question
_____________

now if i do >> String.valueOf(p) what it will return???

will it return a String represntation of object p??????? but what is
the meaning of that??

does it mean after conversuion object p will have only field String
(viz "test")??? other fileds will be lost???


i am not sure about the meaning of the String representation of an
object.can you explain what does it mean???

another question
________________

instead of doing String.valueOf(p) if i did p.toString()

would it give the same result??????



can you give a small code to experiment what is going on ??

thanks

January 27, 2004, 5:24 PM
iago
I *think* that String.valueOf(Object o) just calls o.toString(), so to answer both your questions it will either print out the default toString(), which is pretty much garbage, or it will print out whatever you override toString() with.

Note: use less question marks. It's annoying :P
January 27, 2004, 5:41 PM
touchstone
ok....but what is the meaning of string representation of object?

for example, string representation of integer means something like "123"...is not it?

do you mean string representaion of object is a garbage thing?

January 27, 2004, 6:45 PM
Kp
He means a String object. The default toString method returns a String that, while not null, is not useful to most people. To provide for printing of your object, you should override the toString() method.
January 27, 2004, 7:17 PM
iago
yes, what kp said. If you want to give a meaningful value for your object, do this:

public String toString()
{
return "A good readout for your object";
}

by default, a string object does that for you by returning the string, and most objects will have some default way of doing it.
January 27, 2004, 8:22 PM

Search