...
In this noncompliant code example, the controlling expression in the if
statement is an assignment expression.:
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b) { if (a = b) { /* ... */ } } |
...
The conditional block shown in this compliant solution only executes when a
is equal to b
.:
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b) { if (a == b) { /* ... */ } } |
...
When the assignment is intended, this compliant solution clarifies the programmer's intent.:
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b) { if ((a = b) == true) { /* ... */ } } |
...
It may be clearer to express the logic as an explicit assignment followed by the if
condition.:
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b) { a = b; if (a) { /* ... */ } } |
...
In this noncompliant code example, an assignment expression appears as an operand of the &&
operator. :
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b, boolean flag) { while ( (a = b) && flag ) { /* ... */ } } |
...
When the assignment of b
to a
is unintended, this conditional block is now executed only when a
is equal to b
and flag is true
.:
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b, boolean flag) { while ( (a == b) && flag ) { /* ... */ } } |
...
Exceptionally, it is permitted to use the assignment operator in conditional expressions when the assignment is not the controlling expression (that is, the assignment is a sub-expressionsubexpression), as shown in the following compliant solution.:
Code Block | ||
---|---|---|
| ||
public void assignNocontrol(BufferedReader reader) throws IOException{ String line; while ((line = reader.readLine()) != null) { // ... work with line } } |
...