Misunderstanding the prefix increment

Viewed 52

I don't understand how this method works. I run the recur method and the output starts at 98, gets incremented and I can't seem to understand what's going on later. The output I expected is:

a=98
a=99
a=99
a=100
a=100
a=101

But the actual output is:

a=98
a=99
a=100
a=101
a=100
a=99

I found this exercise in a local java testing forum. So, any explanations would be useful for me.

public  class Test  {

    public static void main(String[] args) {
        recur(98);
    }
    public static void recur(int a) {
        if (a <= 100) {
            System.out.println("a=" + a);
            recur(++a);
            System.out.println("a=" + a);
        }
    }
1 Answers
recur(98)
    print "a=98"
    recur(99)
        print "a=99"
        recur(100)
            print "a=100"
            recur(101)
                do nothing
            print "a=101" // that's the value of a in recur(100) after being incremented once
        print "a=100" // that's the value of a in recur(99) after being incremented once
    print "a=99" // that's the value of a in recur(98) after being incremented once

What you might be missing is that a is a local variable, which means each execution of recur() has its own copy of that variable, and changing the value in one execution doesn't affect the value of the local variable of other executions.

Related