Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can someone explain the output of this code?

 
Dilshad Syed
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<code>
public class Test
{
public static void main(String[] args) {
System.out.println("AAA");
System.out.println(new Test());
}

public String toString() {
System.out.println("###");
return "Z";
}
}
</code>
<ad>THANKS<vance>
 
S Dave
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the output is:
AAA
###
Z
because, System.out.println calls the toString() method of the class of which the object is mentioned and in the above code, the toString() method has been overridden, to print ### and return Z. if it was not overrridden then the o/p would have been:
AAA
Test5@72993cb2
By default, the toString() method of Object class returns the name of the class @ hashcode(i think).
 
Dilshad Syed
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My mistake, I wanted to ask the output of the following code:
<code>
public class Test {
public static void main(String[] args) {
System.out.println("AAA" + (new Test()));
}
public String toString() {
System.out.println("###");
return "Z";
}
}
</code>
It seems bizarre that the output is:
###
AAAZ
Can someone explain?
 
S Dave
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when the System.out.println in main() calls the overridden toString() method, the System.out.println in toString() prints out - ### first and the returned value which is Z is concatenated with AAA and printed as the 2nd statement in the System.out.println in the main function.
hence the o/p:
###
AAAZ
[This message has been edited by Sweekriti Engineer (edited March 09, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic