Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why the ouput is like this ?

 
andy lau
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jackie Wang
Ranch Hand
Posts: 315
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
even the main is not explicitly call toString(), the "B" can still but printed out?
Thanks!
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
andy lau
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic