Michael
Michael

Reputation: 63

Recursion theory in Java

Oracle's documentation say's that there are three parts to creating an object (Declaration, Instantiation and Initialization). It also 'implies' that they "come in order", but it doesn't say this explicitly (although this generally seems to be true).

So, I am wondering if, based on the fact that the improperly coded constructor in my example will result in recursion, is it possible in this case (with regards to the sequence of events) that an attempt to instantiate the object occurs first and that (again, in this case) because of recursion the object reference declaration never occurs....?

public Test(){
 Test t1 = new Test();

}

Upvotes: 0

Views: 137

Answers (6)

Peter Lawrey
Peter Lawrey

Reputation: 533530

Declaration always comes first, in fact it can happen at the start of the method, no matter where you first mention a variable (as they are created at once)

Failure to instantiate, can result in intialisation not occurring.

If a constructor does not exit normally (you will get a StackOverflowError here) the declared field or variable will not be set, an error will be thrown instead.

In the above example t1 will not be set at any point.

"an assignment operator is read from right to left..."

It may be helpful to think of

Test t1 = new Test();

as

Test t1;
t1 = new Test();

Upvotes: 1

ConMan
ConMan

Reputation: 1652

What you have here is an example of infinite recursion, as there is nothing there to allow us to exit the recursive loop. As others have previously said, this will cause a stack overflow error, as the JVM will continually create and assign a memory allocation to the Test object until it runs out of space in memory.

Upvotes: 0

alex
alex

Reputation: 1

Yes. It is recursive and will overflow the stack. Best way to test it out is using a debugger.

Upvotes: -1

Tripp Kinetics
Tripp Kinetics

Reputation: 5439

You need to declare an instance of the class Test in order for your recursion to get kicked off in the first place. However, the instantiation for the object never returns, so the declaration never succeeds.

Upvotes: 0

Edwin Torres
Edwin Torres

Reputation: 2864

This is easy enough to try yourself. Try it and note the result.

public Test()
{
    Test t1 = new Test();
}

public static void main(String[] args) 
{
    Test t = new Test();
}

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 68935

public Test(){
 Test t1 = new Test();

}

New instances of class Test will continue to be created until all your stack space is used up and you JVM will shutdown giving stack overflow error.

Upvotes: 2

Related Questions