programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Need help to understand operator precedence for unary operators

Jitender Singh Tanwar
Greenhorn
Posts: 2
Hi,
I am reading OCA Java SE8 Programmer 1 study guide in which chapter 2 have a table for operators precedence and Post-unary operators (exp++, exp--) are shown having higher precedence than pre-unary operators(++exp, --exp). Now let's look at below example:
int i =13;
int y = --i + --i + i++ * 3;

Now if we apply the above rule, it should be calculated as int y = --i + --i + 13*3; int y = 13 + 12 + 39 = 64. But when I run this I am actually getting 56. That means it is simply evaluated as int y = 12 + 11 + 11*3 = 56.
Which means post and pre unary operators are considered having equal precedence and evaluated from left to right.

I came to know from book itself that authors of the book are moderators on this site, so would like to confirm what is correct order of precedence?

Regards,
Jitender Singh

Knute Snortum
Sheriff
Posts: 4281
127
• 1
Welcome to the Ranch!

Post inc/dec do have the highest precedence but their action happens after evaluation.

Jitender Singh Tanwar
Greenhorn
Posts: 2

I have gone through 2 similar threads given below:
http://www.coderanch.com/t/649218/ocajp/certification/wiley-oca-book-error-unary
http://www.coderanch.com/t/581656/java-programmer-SCJP/certification/understanding-operator-precedence-evaluation

I understand now how it happens.

Henry Wong
author
Sheriff
Posts: 23295
125

As the OP already figured out, precedence and evaluation order are two different things... so this is a side note.

IMO, precedence between pre and post operators doesn't matter. They are unary operators, and they can't be chained (as they only operate on variables), so there is no difference between a precedence of one or two... they both have the "highest" precedence on the table. The difference comes from the other operators listed on the precedence table, and even then, it is likely separated because they have different associativity.

Henry

 It is sorta covered in the JavaRanch Style Guide.