class C { public static void main(String arg[]) { System.out.println("A"+new C()); } public String toString() { System.out.print("B"); return "C"; } } The output is :BAC can you tell me why?
1. First JVM has to compute "A"+new C(). At this point nothing is printed yet, computation is going in memory. 2. new C() calls toString() method of C class 3. Within toString() method "B" is printed (it is the first thing that is getting printed!!!) 4. toString() returns "C". "A"+"C" is computed 5. First println is executed, printing "AC". Shura
Because of the concatenation of the new C object with the String "A", the C object will automatically have the toString() method called on it in order to convert it to a String format so that it can be output. Corey
do you mean that no matter when and where i creat an object using the ''new'' keyword will cause the toString() method of that object to be executed automaticly? thanks!
Originally posted by andy lau: [QB]do you mean that no matter when and where i creat an object using the ''new'' keyword will cause the toString() method of that object to be executed automaticly? [QB]
No! The toString() method is not called when the object is created, but any time the object needs to be displayed as a String. The purpose of the "toString" method is to display the object in a String. Corey