yeppe yeppe - 2 months ago 6
Java Question

Java Recursive function trick

Could anyone explain the output of this program? Why is the is the second value 7?

Not able to understand recursive function call

go(this)


public class ThisIsTricky {

int state = 0;

public ThisIsTricky(int s) {
state = s;
}

public static void main(String[] args) {
ThisIsTricky obj1 = new ThisIsTricky(1);
ThisIsTricky obj2 = new ThisIsTricky(2);

System.out.println(obj1.go(obj1) + "" + obj2.go(obj2));
}

int go(ThisIsTricky thisIsTricky) {
if (this.state == 2) {
thisIsTricky.state = 5;

go(this);
}
return ++this.state;
}

}


Output:-

2 7

Answer

The important thing to notice is that state is a member variable, so it is not shared between obj1 and obj2. Each has its own value (1 and 2, respectively).

Why is the output 7 for obj2? The condition (this.state == 2) is true for obj2, so you go recursively into go(this). Now the condition is not true anymore because state was changed to 5, so state gets incremented. Recursive call ends and you now return to the calling function (after go(this)) and state gets incremented again. Therefore, 5+1+1 = 7.