aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt about output. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt about output." Watch "doubt about output." New topic
Author

doubt about output.

Deep Chand
Ranch Hand

Joined: Dec 17, 2002
Posts: 133
Hi,
In the following piece of code, if you invoke 'java Test' then it throws
StackOverFlowError because of the object creation in the constructor itself. However, the output is 'Exception caught' followed by lots of 'in cons'. My doubt is how come the execution reaches the line 2. Any ideas?
Thanks,
Deep
public class Parcel {
Parcel() {
try{
Parcel p = new Parcel(); // line 1
System.out.println("in cons"); // line 2
}
catch (Error e) {
System.out.println("Exception caught");
}
}
}
class Test {

public static void main(String [] args) {
Parcel p = new Parcel();
}
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

When memory is not sufficient OutOfMemoryError is thrown and it is caught.
All other objects in the recursive list will be creted and so system.out statement.


Groovy
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
Hi Deep,
The error that caused the 'Exception caught' message was actually thrown by the last call to the constructor Parcel(). The message 'in cons' was created by the objects before that.
If you look at the constructor of Parcel(), it is calling itself. So, the first call will not return unless the 2nd call returns, and so on. In short, you have an endless loop.
The message 'in cons' will be printed only after the call to Parcel() returns. So, the first call is the last one to exit, and the last call is the first one to exit the try clause. The last call returns an error so it is the first one to print the message 'Exception caught'.
[ September 04, 2003: Message edited by: Alton Hernandez ]
 
 
subject: doubt about output.