Java Reference
In-Depth Information
58. Use parentheses for precedence of operation
Programmersfrequentlymakeerrorsregardingtheprecedenceofoperatorsbecauseofthe
unintuitive low precedence levels of & , | , ^ , << , and >> . Avoid mistakes regarding preced-
ence through the suitable use of parentheses, which also improves code readability. The
precedence of operations by the order of the subclauses is listed in the Java Tutorials
[Tutorials 2013].
Although it advises against depending on parentheses for specifying evaluation order,
The CERT ® Oracle ® Secure Coding Standard for Java [Long2012],“EXP05-J.Donot
write more than once to the same variable within an expression,” applies only to expres-
sions that contain side effects.
Noncompliant Code Example
The intent of the expression in this noncompliant code example is to add the variable
OFFSET to the result of the bitwise logical AND between x and MASK .
Click here to view code image
public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return x & MASK + OFFSET;
}
According to the operator precedence guidelines, the expression is parsed as
x & (MASK + OFFSET)
This expression is evaluated as follows, resulting in the value 0:
x & (1337 - 1337)
Compliant Solution
This compliant solution uses parentheses to ensure that the expression is evaluated as in-
tended:
Click here to view code image
public static final int MASK = 1337;
public static final int OFFSET = -1337;
Search WWH ::




Custom Search