• Welcome to Valhalla Legends Archive.
 

conversion of object to string

Started by touchstone, January 27, 2004, 11:24 AM

Previous topic - Next topic

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


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
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


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?


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.
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

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.
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*