1

I was trying out to run the below code sample but getting StackOverflow error. It seems to stuck up in the infinite loop. Can anybody help me out in knowing what's going on in here?

Please find below code snippet

public class ConstructorExample {

    private ConstructorExample c1 = new ConstructorExample();

    public ConstructorExample(){
        throw new RuntimeException();
    }

    public static void main(String[] str){
        ConstructorExample c = new ConstructorExample();
    }
}

2 Answers2

2

You have the member private ConstructorExample c1 = new ConstructorExample(); in the ConstructorExample class.

When you instantiate a first instance of ConstructorExample, the JVM allocates memory for that ConstructorExample, then tries to instantiate the first member, c1. This instantiation starts with allocating memory for another ConstructorExample instance, and so on.

Also, the runtime exception is irrelevant because the member initializer is executed before the constructor.

user3711864
  • 349
  • 2
  • 10
0

Its as expected. The instance creation of ConstructorExample is attempted from the main method, for which the instance variable is initialized before calling the constructor.

private ConstructorExample c1 = new ConstructorExample();

Which then repeats the cycle again and keep on allocating more and more memory causing stackoverflow, without even completing to create a single instance fully.

Kedar Parikh
  • 1,241
  • 11
  • 18