Following are two versions of the same program but the instance variable is initialized inside a method in one case; and other outside of it. However, when the program is run, only one of them gives a stack overflow (i.e. it runs infinitely) whereas the other does not. Please explain.
Your code where you are assigning memory to a variable at the class level will give stack overflow error.
It is because when you assign memory to an object, it allocates memory space to all the instance variables and the functions.
In you case you are creating an object "a" of class X. When you do this, the JVM will start allocating memory to the instance variables.
In your case, "b" is an instance variable to which you are assigning memory at the class level. Since "b" is also an object, the JVM will
again go to assign memory space to the instance variables of class X (which is b in our case). Hence this process will keep on going
till you run out of memory.
So in order to avoid this problem, if you are creating an object of a class as its instance member, avoid assigning memory to it at the class level
or in the constructor.
posted 6 years ago
Thanks for your reply Richa!
However, Java allows such memory assignments at class level (in fact I got one such example in the book 'Head First Java' page #239). So, in case you create (and assign) an object to a different class than X (at the class level), it works!
The problem here is: The constructor called is of the same class as the one in which the code exists in the first place. So there is a kind of recursive call!
However, it is the same with both the Versions (i.e. both are kind of recursive calls). But, only one goes for the stack overflow. Not sure why...
Rajarshi Rakshit wrote:However, it is the same with both the Versions (i.e. both are kind of recursive calls). But, only one goes for the stack overflow. Not sure why...
No, they're not. In the first case, you construct a new object when instantiating the class. That, in turn, instantiates another object of the same class, and so on.
In the second example, another object is only created when you call printing(), and that will not start a recursion.
Life is full of choices. Sometimes you make the good ones, and sometimes you have to kill all the witnesses.