Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

conversion of object to string

  Asked By: Dukker    Date: Nov 02    Category: Java    Views: 664
  

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 ??

Share: 

 

5 Answers Found

 
Answer #1    Answered By: Holly Brown     Answered On: Nov 02

The String.valueof(Object) method uses the output from Object.ToString()

The default behavior of this method is:

getClass().getName() + '@' + Integer.toHexString(hashCode())

All this is from the Java 1.4.2 documentation. I advise that you
download it. Sun has provided some of the most complete documentation
I have ever seen.

test code:

public class ValueTest{
int i;
String s;

ValueTest(){
i = 3;
s = "test";
}

public static void main(String[] args){
ValueTest t = new ValueTest();

System.out.println(String.valueOf(t));
System.out.println(t.toString());
}
}

 
Answer #2    Answered By: Maliha Malik     Answered On: Nov 02

Sorry, forgot to mention that if you want a different behavior, just
override the toString method in your class.

 
Answer #3    Answered By: Edward Jones     Answered On: Nov 02

thanks, i have tested it both way....its giving me the result as
expected.

 
Answer #4    Answered By: Lewis Welch     Answered On: Nov 02

valueOf() is used to convert all the data types into
strings.toString() is used to convert objects into
strings.If u pass a object  into valueOf() methos it
internally calls toString() method.
hope i clarified atleast some of ur doubts

 
Answer #5    Answered By: Mike Stephens     Answered On: Nov 02

I dont know what you want to do, but to convert object  to String, just do
this:
Ojbect[] varobject = {"First String", new Integer(1000), new
Double(100.55)};
String test  = (String)varobject[0];

In your case:
sample p = new sample(12,45.60,"test");
String x = String.valueOf(p.x);
String y = String.valueOf(p.y);
String s = p.s;

 
Didn't find what you were looking for? Find more on conversion of object to string Or get search suggestion and latest updates.




Tagged: