Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Operator precedence  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,
Given this code

when i=0 I would have thought it didn't compile because I evaluated it like this
iA[0] = 0 = 30 -> 0 = 30
but apparently I got the rules of operator precedence wrong. How is evaluated please?
thanks


 
Stephan van Hulst
Saloon Keeper
Posts: 7190
118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The assignment operator associates to the right, meaning the precedence is like so:

When two operators have the same precedence, you must look at whether they are left- or right-associative. This is actually pretty easy because in Java, only prefix operators and assignment operators are right-associative. For prefix operators you don't even have to remember the rule, because it follows naturally from the way they are written:

So really, the only thing you have to remember is that when you have an expression that consists of multiple (compound) assignment operators, the assignment happens from right to left.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!