Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java operator precedence with assignment

I would be grateful if someone could please explain why the following is occuring. Thanks a lot.

boolean b = true;
// Compiles OK.
// The LHS "assignment operand" requires no ()parentheses.
if (b=true || b==true);

// Reverse the ||'s operands, and now the code doesn't compile.
if (b==true || b=true);

// Add () around the RHS "assignment operand", and the code now compiles OK.
if (b==true || (b=true));

Edit -

BTW, the compilation error for code line #2 is: "unexpected type", and occurs where the short-circuit OR operator is located:

if (b==true || b=true);
//          ^ "unexpected type" compilation error occurs here.

Edit 2 -

Please note that the code fragments found in this question are examples of "highly artificial Java coding", and consequently would not be seen in professionally written code.

Edit 3 -

I'm new to this incredibly useful website, and I've just learnt how to make and upload screenshots of Java's compilation messages. The following image replicates the information that I provided in my first "Edit" above. It shows the compilation error for example code line #2.

Code line #2 compilation error

like image 706
user2911290 Avatar asked Nov 15 '13 10:11

user2911290


1 Answers

The assignment operator = has lower precedence than the logical or operator || so that you can use the logical operator in an assignment without extra pairs of parentheses. That is, you would want to be able to write

a = b || c;

instead of being forced to write a = (b || c).

Unfortunately, if we work with operator precedence only, this rule also applies to the left hand side of the expression. a || b = c must be parsed as

(a || b) = c;

even if what you intended was a || (b = c).

like image 146
Joni Avatar answered Sep 23 '22 15:09

Joni