Caffeinated
Caffeinated

Reputation: 12486

In Java, when exactly does the post-increment operation occur?

I'm looking at this Java code:

        while (n-- != 0) {
            if (searchMe.charAt(j++) != substring.charAt(k++)) {
                continue test;
            }
        }

I am confused about when, exactly, the n-- operation takes place. Is it after the if statement?

Upvotes: 0

Views: 653

Answers (3)

hidro
hidro

Reputation: 12521

-- or ++ operators if put after operand will happen after the statement that contains it finishes. If put before operand then it will happen before that statement.

In this case the statement is while so it will happen after it, meaning after evaluation of condition in the while statement.

Upvotes: 1

Harish Talanki
Harish Talanki

Reputation: 876

When the while loop runs for the first time, the value of n is checked if its not equal to zero(because it is post decrement).

Once the condition is evaluated, i.e. after it comes inside the while loop, the value of n will be decremented by one(n-1). And this new value will be used inside the while loop for that particular iteration.

Next iteration when the while loop check the condition, value (n-1) is checked if its equal to zero and so on.

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234795

The n-- operation happens each time the while condition is evaluated; specifically when the left-hand side of the != operator is evaluated. It has nothing to do with the if statement. The while condition is evaluated at the start of each loop iteration; if it evaluates to true, then the body of the while loop (the if statement) is executed, but that's well after the n-- operation has finished. (But of course, then there's the next loop iteration.)

Upvotes: 5

Related Questions