tarmogoyf
tarmogoyf

Reputation: 327

Misunderstanding the prefix increment

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);
        }
    }

Upvotes: 2

Views: 58

Answers (1)

Eran
Eran

Reputation: 393771

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.

Upvotes: 5

Related Questions