Java Reference
In-Depth Information
Although the programmer's intent could have been to assign
b
to
a
and test the value
of the result, this usage frequently occurs when the programmer mistakenly uses the as-
signment operator
=
rather than the equality operator
==
.
Compliant Solution
The conditional block shown in this compliant solution only executes when
a
is equal to
b
.
public void f(boolean a, boolean b) {
if (a == b) {
/* ... */
}
}
Unintended assignment of
b
to
a
cannot occur.
Compliant Solution
When the assignment is intentional, this compliant solution clarifies the programmer's in-
tent:
public void f(boolean a, boolean b) {
if ((a = b) == true) {
/* ... */
}
}
Compliant Solution
It is clearer to express the logic as an explicit assignment followed by the
if
condition:
public void f(boolean a, boolean b) {
a = b;
if (a) {
/* ... */