File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

doubt about output.

Deep Chand
Ranch Hand

Joined: Dec 17, 2002
Posts: 133
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?
public class Parcel {
Parcel() {
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: 8927

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.

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 ]
I agree. Here's the link:
subject: doubt about output.
It's not a secret anymore!