Oceana Wickramasinghe wrote:Oh,I thought it would only create a reference variable, not the object.
This would declare a reference variable:
A a;
Whereas this declares a reference variable and creates a new object.
A a=new A();
new always results in a new object being created.
Oceana Wickramasinghe wrote:Another question, isnt the stackoverflow error related to the stack, but objects are created on heap correct? So why does it result in a stack overflow?
The
word "stack" also refers to the execution stack, which keeps track of which methods are called. Everytime a method is called, then that call is added to the stack, because the program needs to know where to return to when the method has completed. There's a limited amount of memory for this, and when it runs out you get a "stack overflow". So this error tends to be caused by a recursive method calls that doesn't have an exit condition. It's not really the memory running out because there are too many objects that's causing the error (that would give you an
OutOfMemoryError), it's the stack overflowing because the
A constructor is effectively calling itself.