Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow (->) operator precedence/priority is lowest, or priority of assignment/combined assignment is lowest?

JLS:

The lowest precedence operator is the arrow of a lambda expression (->), followed by the assignment operators.

Followed in which direction (increasing priority, decreasing priority)? - "followed" means assignment has higher priority or lower priority (with respect to arrow operator)? I guess, in increasing, because "lowest" (for arrow) means absolutely lowest.

As I understand, arrow (->) should be at the very bottom of this Princeton operator precedence table (that is below all assignment operators), thus arrow (->) having 0 (zero) priority Level (as per that table).

Am I correct in my understanding?

ExamTray seems to say that arrow priority is at least same as assignment... Plus clarified that arrow associativity is Left->To->Right (unlike assignment). I didn't find any JLS quote for arrow associativity.

I always used to think that assignment priority is principally lowest for a reason.

like image 711
Code Complete Avatar asked Nov 27 '19 11:11

Code Complete


People also ask

Which operator has the lowest priority precedence?

D) | | - This operator falls under the category of Logical OR and has the lowest priority as compared to all the above-mentioned operators.

What is the order of precedence highest to lowest?

Explanation: Order of precedence is (highest to lowest) a -> b -> c -> d. 2.


1 Answers

Note the sentence preceding the quoted JLS text:

Precedence among operators is managed by a hierarchy of grammar productions.

The grammar of the Java language determines which constructs are possible and implicitly, the operator precedence.

Even the princeton table you’ve linked states:

There is no explicit operator precedence table in the Java Language Specification. Different tables on the web and in textbooks disagree in some minor ways.

So, the grammar of the Java language doesn’t allow lambda expressions to the left of an assignment operator and likewise, doesn’t allow assignments to the left of the ->. So there’s no ambiguity between these operators possible and the precedence rule, though explicitly stated in the JLS, becomes meaningless.

This allows to compile, e.g. such a gem, without ambiguity:

static Consumer<String> C;
static String S;
public static void main(String[] args)
{
  Runnable r;
  r = () -> C = s -> S = s;
}
like image 80
Holger Avatar answered Oct 11 '22 11:10

Holger