So for binary operators on booleans, Java has &
, |
, ^
, &&
and ||
.
Let's summarize what they do briefly here:
- JLS 15.22.2 Boolean Logical Operators &, ^, and |
- JLS 15.23 Conditional-And Operator &&
- JLS 15.24 Conditional-Or Operator ||
For
&
, the result value istrue
if both operand values aretrue
; otherwise, the result isfalse
.For
|
, the result value isfalse
if both operand values arefalse
; otherwise, the result istrue
.For
^
, the result value istrue
if the operand values are different; otherwise, the result isfalse
.The
&&
operator is like&
but evaluates its right-hand operand only if the value of its left-hand operand istrue
.The
||
operator is like|
, but evaluates its right-hand operand only if the value of its left-hand operand isfalse
.
Now, among all 5, 3 of those have compound assignment versions, namely |=
, &=
and ^=
. So my question is obvious: why doesn't Java provide &&=
and ||=
as well? I find that I need those more than I need &=
and |=
.
And I don't think that "because it's too long" is a good answer, because Java has >>>=
. There must be a better reason for this omission.
From 15.26 Assignment Operators:
There are 12 assignment operators; [...]
= *= /= %= += -= <<= >>= >>>= &= ^= |=
A comment was made that if &&=
and ||=
were implemented, then it would be the only operators that do not evaluate the right hand side first. I believe this notion that a compound assignment operator evaluates the right hand side first is a mistake.
From 15.26.2 Compound Assignment Operators:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
As proof, the following snippet throws a NullPointerException
, not an ArrayIndexOutOfBoundsException
.
int[] a = null;
int[] b = {};
a[0] += b[-1];