• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Can someone explain the output of this code?

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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>
 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic