I am really confused with tostring........ Why does this program give an output of 10. There is no way in the program that I am refering to the method tostring, still why does it executes the tostring method.. Mysterious strings.........
Take a look at <code>java.io.PrintStream</code> class which is contained in the the System.out reference. There are several <code>println()</code> methods ( overloaded ) but there are only two of them which take the non-primitive argument. They are <code>println( String ) </code> and <code>println( Object )</code> Also, remember that any expression involving a <code>String</code> evaluates to a <code>String</code>. If such expressions has primitives, they too are converted to strings using respective wrapper classes. If the expression has object references, <code>toString()</code> method on such object(s) gets called. Hence, when you pass an object reference to the <code>println()</code> method, the <code>println(Object)</code> version gets called. This method calls the <code>toString()</code> method on the object that is passed in, to convert the object to the string representation. If the ( runtime type of the ) object being passed doesnot implement the <code>toString</code> method, the <code>Object.toString()</code> method gets called due to polymorphism. Now lets look at your example. You are calling the <code>println(Object)</code> version and so at runtime, the <code>toString()</code> method on your object ie., the <code>TestClass</code> object gets called. This returns the string <code>"TestClass.s = "+this.s;</code>. Hence the result To make this code more interesting, just comment out the <code>toString()</code> method in your <code>TestClass</code> and run the program. Observe what happens ! Ajith [This message has been edited by Ajith Kallambella (edited November 03, 2000).]
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Hi Shalini, Nothing Mysterious about strings. You have overrided the toString() method in your class and asking why it is getting executed. This is really fun. By the way do you know when your JVM will invoke toString() method? If you pass something funny inside the System.out.println(). Here you have passed the class reference "this" inside the System.out.println(). The JVM is confused with your parameter so it invoked toString() overrided by you in the class. You remove your toString() then you will see funny results. try. solaiappan