Today, while playing with Java code and Eclipse, I falled to the following code:
package test;
/**
* @author Hong Nam NGUYEN -- Created: 18 oct. 07 - 15:23:41
*/
public class Recursion
{
private int x;
private Recursion obj;
public void init(int x)
{
this.x = x - 1;
System.out.println("x = " + this.x);
while (this.x > 7)
{
obj = new Recursion();
obj.init(this.x);
}
}
public static void main(String[] args)
{
Recursion obj = new Recursion();
obj.init(10);
System.out.println("Finish");
}
}
I thought that the program will print out
x = 9
x = 8
x = 7
Finish
and stop!
But not, the real result is
x = 9
x = 8
x = 7
x = 7
x = 7
x = 7
….
and infinite loop ??
By reinspecting the code, I found that I have made an error. The variable x is an instance variable, so it belongs to each instance of the class Recursion, but not to the class at a whole. When a new instance is created (Recursion obj = new Recursion();) and the init method called, the following instruction is executed: this.x = x – 1;, but not the same x each time. In fact, the x of the very first instance has the value 9 (= 10 – 1), and then, it never change any more ! That’s why I get the infinite loop.
To correct this problem, there are (at least) two solutions:
– make x a static variable (static private int x;)
– or add code that changes x in the while loop
while (this.x > 7)
{
obj = new Recursion();
obj.init(this.x);
this.x--;
}
!!! The results of the two solutions are not the same, but the loop finite.