aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why the ouput is like this ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why the ouput is like this ?" Watch "why the ouput is like this ?" New topic
Author

why the ouput is like this ?

andy lau
Ranch Hand

Joined: Apr 08, 2002
Posts: 51
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?
Shura Balaganov
Ranch Hand

Joined: Apr 22, 2002
Posts: 664
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


Any posted remarks that may or may not seem offensive, intrusive or politically incorrect are not truly so.
RusUSA.com - Russian America today - Guide To Russia
Jackie Wang
Ranch Hand

Joined: Apr 18, 2002
Posts: 315
even the main is not explicitly call toString(), the "B" can still but printed out?
Thanks!
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
andy lau
Ranch Hand

Joined: Apr 08, 2002
Posts: 51
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!
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why the ouput is like this ?