...
Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.
These When an expression contains side effects, these two requirements can be counterintuitive when expressions contain side effectsyield unexpected results. Evaluation of the operands proceeds left to right, without regard to operator precedence rules and indicative parentheses; evaluation of the operators, however, obeys precedence rules and parentheses.
...
Code Block | ||
---|---|---|
| ||
class BadPrecedence {
public static void main(String[] args) {
int number = 17;
int[] threshold = new int[20];
threshold[0] = 10;
number = (number > threshold[0]? 0 : -2)
+ ((31 * ++number) * (number = get()));
// ...
if (number == 0) {
System.out.println("Access granted");
} else {
System.out.println("Denied access"); // number = -2
}
}
public static int get() {
int number = 0;
// Assign number to non zero value if authorized else 0
return number;
}
}
|
...
Code Block | ||
---|---|---|
| ||
int number = 17; final int authnum = get(); number = ((31 * (number + 1)) * authnum) + (authnum > threshold[0]? 0 : -2); |
Exceptions
EXP05-EX1: The increment and decrement operators (++)
and (--)
read a numeric variable, and then assign a new value to the variable. These are well-understood and are an exception to this rule.
EXP05-EX0EX1: The logical operators ||
and &&
have well-understood short-circuit semantics, so expressions involving these operators may do not violate this rule. Consider the following code:
...
Although the conditional expression violates appears to violate this rule, this code is compliant because the subexpressions on either side of the &&
operator do not violate it. Each subexpression has exactly one assignment and one side effect (the reading of a character from in
).
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b53ca4a0a665ec3f-7328c4c0-42b64d16-8cb6b9a3-91eb366cefe047685d75fcb0"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [§15.7, Evaluation Order | http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7] | ]]></ac:plain-text-body></ac:structured-macro> |
|
...