wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can someone explain the output of this code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can someone explain the output of this code?" Watch "Can someone explain the output of this code?" New topic
Author

Can someone explain the output of this code?

Dilshad Syed
Greenhorn

Joined: Mar 05, 2001
Posts: 29
<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

Joined: Jan 28, 2001
Posts: 103
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

Joined: Mar 05, 2001
Posts: 29
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

Joined: Jan 28, 2001
Posts: 103
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).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can someone explain the output of this code?
 
Similar Threads
Semicolon in string?
Object constructor and initialization
practice question: what is the output?
[this]....
Difference of double quotes