Reputation: 2619
At the very last condition, I was expecting to get the condition evaluated starting from the expression on the left of operator "&&" which becomes true and then the statement on the right . However, I am getting compilation error here saying "syntax error on token "=", != expected". Any explanation on this problem would be of great help.
boolean boolTrue=Boolean.TRUE;
boolean assignBool=Boolean.FALSE;
int ten=10;
//eventually evaluates to true , runs okay
if(assignBool=boolTrue){
System.out.println("Executed");
}
//evaluates to true && true: runs correctly
if( assignBool=boolTrue && ten==10 )
System.out.println("Executed");
//evaluates to true && true : runs correctly
if( ten==10 && (assignBool=boolTrue) )
System.out.println("Executed");
/*was supposed to evaluate to true && true : but gives compile error
compiler expects me to use '!=' or '==' operator though the second statement ultimately evaluates to true
as in above case*/
if( ten==10 && assignBool=boolTrue )//Compile error
System.out.println("Executed");
EDIT: Thanks for the answer. To check if it was operatar precedence issue, I ran same case in for loop and YES, that was it .
boolean boolTrue=Boolean.TRUE;
boolean assignBool=Boolean.TRUE;
int ten=10;
singleloop:
for(int i=0;((ten==10 && assignBool)==boolTrue);System.out.println("Executed")){
i++;
if(i>10)
break singleloop;
}
Upvotes: 3
Views: 635
Reputation: 282805
it's being evaluated as if((ten==10 && assignBool)=boolTrue )
which means you are trying to assign to a constant.
Upvotes: 1
Reputation: 234795
The compiler is trying to evaluate the last if
as if it were written
if( (ten==10 && assignBool)=boolTrue )
which makes no sense because the left side is not an lvalue (to borrow some vocabulary from C). This is because &&
has higher precedence than =
in Java.
Upvotes: 5
Reputation: 28302
I assume from your code that you are trying to play around and actually want to assign boolTrue to assignBool.
The problem is the order of operators. The && has higher precedence than = (source). It is creating a bool by anding with the ten==10 expression. The result is a non-lvalue (an expression that cannot be written to). Your expression is equivalent to the fully parenthesized:
((ten == 10) && assignBool) = boolTrue
As you've already found out, the following is the way to do it:
ten==10 && (assignBool=boolTrue)
Upvotes: 3
Reputation: 70564
As you can see from the nice table in the Java Tutorial, the assignment operator has the lowest precedence among all operators. That is, the expression
ten==10 && assignBool=boolTrue
is evaluated as
(ten==10 && assignBool) = boolTrue
but the left hand expression is not assignable.
If you want different precedence, you must use brackets, i.e.
ten==10 && (assignBool = boolTrue)
Upvotes: 3
Reputation: 412
I don't know java but it's probably binding && more strongly than your other operators.
Upvotes: 2