Tuesday, March 17, 2015

What happens when creating instance inside constructor of the same class - frequently asked questions on core java

Q: What happens when creating instance inside constructor of the same class - frequently asked questions on core java?

package com.sat.test.java;
public class TestConstructor {
public static void main(String[] args) {
A a = new A();
}
}
class A{
A(){
System.out.println("class A()");
new A();
}

}



OUTPUT

class A()
class A()
class A()
.
.
.

class A()
class A()
class A()
class A()
class A()
class A()
class A()
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.SingleByte.withResult(Unknown Source)
at sun.nio.cs.SingleByte.access$000(Unknown Source) 


Explanation: When we call new A() from A() constructor it will try to create as many instances as it can but when it got exhausted it will throw StackOverflowError.