Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why toString is called in this example? 1

Status
Not open for further replies.

prosper

Programmer
Sep 4, 2001
631
HK
class Abc
{
private int a;
private int b;
private int c;
Abc(int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
public String toString()
{
return "a= "+a+",b= "+b+",c="+c;
}
}

class useAbc
{
public static void main(String args[])
{
Abc theAbc = new Abc(11,13,48);
System.out.println("here it is "+theAbc);
}
}
Where can I find more information about this usage? Can I find it in specification or jdk doc?
 
Look at the documentation for java.lang.Object.toString()


-pete
I just can't seem to get back my IntelliSense
 
prosper,
to add to pete's comment, Object has a toString method so that you can use System.out.println <object>.toString to print out the name of the object. Pretty useful when you are debugging etc because you can see the name of the object! Hence, all subclasses under Object has this method.
 
hey guys I want clarification.

System.out.println(&quot;here it is &quot; + theAbc);

Does this automatically convert theAbc to a string?





Gary Haran
==========================
 
yes it it. It's an automatic casting to string. look at this
examples:-

int x = 2;
int y = 3;

String.out.println(&quot;xy is &quot; + x + y ); //prints xy is 23
String.out.println(&quot;xy is &quot; + (x + y));//prints xy is 5

the parentheses takes the precedence in the second printout.
Hence, an arithmetic result is produced.

Also, you probably want to read on immutable String objects when you have a chance. There are some good stuff in there.





 
Gary
>> Does this automatically convert theAbc to a string?

Depends on how you define automatic. It calls the Object.toString() method which in the case of class Abc is overridden:
Code:
public String toString()
   {
    return &quot;a= &quot;+a+&quot;,b= &quot;+b+&quot;,c=&quot;+c;
   }


-pete
I just can't seem to get back my IntelliSense
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top