anon
anon

Reputation:

Strange behaviour of the increment operators in Java?

I have to pieces of code:

int m = 4;
int result = 3 * (++m);

and

int m = 4;
int result = 3 * (m++);

After the execution m is 5 and result is 15 in the first case, but in the second case, m is also 5 but result is 12. Why is this the case? Shouldn't it be at least the same behaviour?

I'm specifically talking about the rules of precedence. I always thought that these rules state that parantheses have a higher precedence than unary operators. So why isn't the expression in the parantheses evaluated first?

Upvotes: 1

Views: 359

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503899

No - because in the first case the result is 3 multiplied by "the value of m after it's incremented" whereas in the second case the result is 3 multiplied by "the initial value of m before it's incremented".

This is the normal difference between pre-increment ("increment, and the value of the expression is the value after the increment") and post-increment ("remember the original value, then increment; the value of the expression is the original one").

Upvotes: 7

mrkhrts
mrkhrts

Reputation: 829

Think of it as "increment and get" and "get and increment." For instance, see AtomicInteger, which has the methods incrementAndGet() and getAndIncrement().

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 376052

This is the definition of the operators: m++ evaluates to m, then increments m. It's a "post-increment". Parentheses around it don't change the fact that the operator evaluates to the variable, and also increments it afterward.

Upvotes: 1

Java Drinker
Java Drinker

Reputation: 3167

The difference is when the result is assigned to m. In the first case you have basically (not what it really does, but helps to understand)...

int result = 3 * (m=m+1);

In the second case you have

int result = 3 * m; m = m +1;

Upvotes: 3

Related Questions