• Post Reply Bookmark Topic Watch Topic
  • New Topic

Operator precedence - pre and post incrementation/decrementation  RSS feed

 
Mega Cinol
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm preparing to take OCA exam and found one thing, that is confusing me.

++ and -- operators have the highest priority, so as I understand it, should be evaluated first.
However, please take a look at these two code snippets.

and

As I understand it, in both cases pre decrementation should be evaluated first, so 'a' should be treated as 3 in the whole example, so I should get 'false' in both cases.
Clearly my understanding is incorrect

Could anyone please explain, how does it work with pre and post incrementation and decrementation precedence?

Thanks in advance!
 
Rob Spoor
Sheriff
Posts: 20968
84
Chrome Eclipse IDE Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

While it's true that ++ and -- operators have the highest priority, evaluation still occurs from left to right. It's only that ++ and -- will occur before any other operator.

Let's take your two examples:
--a <= 3 % a is the same as ((--a) <= (3 % a)). First --a is evaluated; a is decreased by 1, and the result is 3. Then 3 % a is evaluated. Since a is now 3, the result is 0. The result is then 3 <= 0 which is false.

3 % a >= --a is the same as ((3 % a) >= (--a)). First 3 % a is evaluated. Since a is still 4, the result is 3. Then --a is evaluated. The result is now 3 >= 3 which is true.
 
Tony Docherty
Bartender
Posts: 3237
79
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you change the last println to

You will be able to see what is happening.
 
Mega Cinol
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now it's clear - thanks!
 
Henry Wong
author
Sheriff
Posts: 23192
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mega Cinol wrote:
++ and -- operators have the highest priority, so as I understand it, should be evaluated first.


Only because I am being pedantic ... First, it is not highest "priority" -- it is "precedence". Second, only the post increment and post decrement are in the highest precedence group. The pre increment and pre decrement, has the next highest precedence. And finally, as already mentioned, precedence and evaluation order are not the same thing.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!