I have this code...
public class BackHanded {
int state = 0;
BackHanded(int s) {
state = s;
}
public static void main(String... hi) {
BackHanded b1 = new BackHanded(1);
BackHanded b2 = new BackHanded(2);
System.out.println(b1.go(b1) + " " + b2.go(b2));
}
int go(BackHanded b) {
if (this.state == 2) {
b.state = 5;
go(this);
}
return ++this.state;
}
}
Why the statement return ++this.state;
executed twice here in the second method call?
EDIT: I expected the output to be 2 6. But I got 2 7.
The method calls itself within itself using recursion. The recursion does not occur on the first invocation since
state != 2
, however the second invocation satisfies the conditionalthis.state == 2
causing the method to recurse.The execution of the second invocation of this method
b2.go(b2)
occurs in this manner:state ==2
we fall into the conditional block.state != 2
so we skip the conditional.++this.state
or 6 and finishes the invocation of itself.++this.state
or 7.