-2
package qwertyuiop;

public class Confusion {
    Confusion com = new Confusion();

    public static void main(String[] args) {
        Confusion con = new Confusion();
        System.out.println(4);
        con.A();
        System.out.println(5);
    }

    public void B() {
        System.out.println(3);
    }

    public void A() {
        System.out.println(4);
        com.B();
        System.out.println(4);
    }
}

I know the code is wrong but I am interested in knowing why this is throwing StackOverflowError. I would also like to know how this code is executing internally.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216

2 Answers2

3

When you create con, the member of it(com) will be created. And when you try to create com, the member of it(another com) will be created. This procedure is repeated until stack overflow.

If you don't want to initiate com multiple times, you can make it a static member:

static Confusion com = new Confusion();
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

Let us start with the basics (which you can skip if you already know about stack and heap):

The main memory for program execution is divided into basically two parts: stack and heap.

In programs, primitives and references to objects are stored in a stack, and the data of an object is stored in a heap, which is referenced by the reference stored in the stack.

Now everytime you use the new keyword, a new slot of memory from the heap is allocated to your object and it's address/reference is stored in the stack.

READ FROM HERE IF YOU KNEW THAT:

Coming to your problem, in your constructor, you call the constructor itself again, and this creates a recursive situation, in which the constructor calls itself again and again, thus the new is executed again and again and hence reference to more and more slots of heap are added to the stack until it runs out of memory.

Hence the exception.

BK1603
  • 150
  • 7