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];
Best Answer
Reason
The operators
&&=
and||=
are not available on Java because for most of the developers these operators are:Example for
&&=
If Java allowed
&&=
operator, then that code:would be equivalent to:
This first code is error-prone because many developers would think
f2()
is always called whatever the f1() returned value. It is likebool isOk = f1() && f2();
wheref2()
is called only whenf1()
returnstrue
.If the developer wants
f2()
to be called only whenf1()
returnstrue
, therefore the second code above is less error-prone.Else
&=
is sufficient because the developer wantsf2()
to be always called:Same example but for
&=
Moreover, the JVM should run this above code as the following one:
Compare
&&
and&
resultsAre the results of operators
&&
and&
the same when applied on boolean values?Let's check using the following Java code:
Output:
Therefore YES we can replace
&&
by&
for boolean values ;-)So better use
&=
instead of&&=
.Same for
||=
Same reasons as for
&&=
:operator
|=
is less error-prone than||=
.If a developer wants
f2()
not to be called whenf1()
returnstrue
, then I advice the following alternatives:or: