Forums Register Login

why the ouput is like this ?

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
even the main is not explicitly call toString(), the "B" can still but printed out?
Thanks!
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
 

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
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 611 times.
Similar Threads
doubt in == for a string operation
How do you think this?
instanceof operator
sequence confusion
String
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 07:09:29.