Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operator precedence

 
chinu sharma
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int k = 1;
int i = +k + k++
On running, the value of i is 2.
((+k) + (k++))
( 1 + 1 )
I can understand this assuming that unary + and postfix operators have the same precedence.
But, according to JLS the postfix operator has higher precedence compared to unary +, so that k++ should be evaluated first and then +k.
((+k) + (k++))
( 2 + 1 )
According to this, answer is 3.
Please explain, why the compiler is not following the precedence given in the JLS.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When expressions with multiple operands are evaluated, they are generally evaluated from left to right. From the JLS, §15.7.1 Evaluate Left-Hand Operand First:

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

Be sure to check out that section of the JLS as I feel it will answer your questions.
I hope that helps,
Corey
 
Brian Joseph
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was evaluating expressions the same way, and when writing code I'd always use parens like any sane person.
But the compiler doesn't evaluate expressions that way. You have the right technique with replacing all the variables with values as a first step.
But the rule you have to follow is this: Evaulate left to right, and respect predecence.
Try this:
i = k++ + k; Now you get 3.
1 (2) + 2 = 3
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic