Search code examples
javavariable-assignmentassignment-operatorassignboolean-expression

Why in java not allowed assignment and boolean operator without brackets


Sorry, for the strange question formulation. If somebody has an idea how to make it better, I will be happy. Lest imagine we have 3 boolean variable:

boolean a = false;
boolean b = false;
boolean c = false;

Java allows to write the folowing:

System.out.println(a=b);
System.out.println(a==b & a==c);

And from this two statements I expected that the following is legal, too.

System.out.println(a=b & a=c);

My question is: why in the second case it isn't allowed, when it is allowed in the first one? In the second case both assignments resolved in boolean and & looks legal for me.


Solution

  • This is because = has a lower priority than & (which, by the way, is a boolean operator in your snippets and not a bitwise operator; it is the same as && except that it does not short circuit).

    Therefore your expression reads (with parens):

    a = (b & a) = c
    

    But you can't assign c to b & a.