• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Errata on unary operator precedence, page 59? (Java OCA 8 Programmer I Study Guide, Sybex)

 
Juliet Smith
Greenhorn
Posts: 9
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to table 2.1 on page 52, post-unary operators have higher precedence than pre-unary operators - however this is ignored in the explanation of the evaluation of the code on the middle of p. 59:

int x = 3;
int y = ++x * 5 /x-- + --x;

If post-unary operators have higher precedence then x-- must be evaluated first resulting in x = 2 and x-- is replaced with 3 i.e:
int y = ++x * 5/3 + --x;
since ++x and --x have the same precedence they are evaluated from left to right giving:
int y = 3 * 5 / 3 + 2;

i.e. y = 5 + 2 = 7

The same result but different reasoning
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Juliet Smith wrote:According to table 2.1 on page 52, post-unary operators have higher precedence than pre-unary operators - however this is ignored in the explanation of the evaluation of the code on the middle of p. 59:

That's really a very common question (confusion) on this forum! You should definitely read this topic and this one as both topics provide excellent explanations (with illustrative code snippets) about the same code snippet. And if you want to learn more about the order of evaluation of (post-)increment (& decrement) operators, this topic is also definitely worth reading. And if you want to learn more about evaluating boolean expressions with short-circuit operators this topic and this one are must-read topics.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic