Java : recursive constructor call and stackoverflow error

后端 未结 5 1961
醉话见心
醉话见心 2020-12-03 20:00

Please help to understand why does the following code

public class HeapQn1 {

    /**
     * @param args
     */
    public HeapQn1() {
        new HeapQn1(         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 20:37

    Whenever the constructor is called, its return address is pushed onto the stack. As the stack is finite and smaller than the heap memory, you are getting error like StackOverflowError rather than OutOfMemoryError.

    The constructor is a method and since the heap memory is much larger than the stack memory, the recursive constructor call resulted in StackOverflowError. Is this correct ?

    Yeah, your wild guess is completely correct. Cheers!

提交回复
热议问题