Programmers frequently make errors regarding the precedence of operators because of the unintuitive low-precedence levels of &
, |
, ^
, <<
, and >>
. Avoid mistakes regarding precedence through the suitable use of parentheses. This also improves code readability unless taken to excess. The precedence of operations by the order of the subclauses are defined in the Java Tutorials [Tutorials 2008].
...
Code Block | ||
---|---|---|
| ||
public static final int MASK = 1337; public static final int OFFSET = -1337; public static int computeCode(int x) { return (x & MASK) + OFFSET; } |
Exceptions
Noncompliant Code Example
In this noncompliant code example, the intent is to add to the string "value=
".
Code Block | ||
---|---|---|
| ||
public class Test{
public static void main(String[] args) {
String s = null;
System.out.println("value=" + s == null? 0 : 1); // prints "1"
}
}
|
However, the precedence rules result in the expression to be printed being parsed as ("value=" + s) == null? 0 : 1
.
Compliant Solution
This compliant solution uses parentheses to ensure that the expression evaluates as intended.
Code Block | ||
---|---|---|
| ||
public class Test{
public static void main(String[] args) {
String s = null;
System.out.println("value=" + (s == null? 0 : 1)); // prints "value=0" as expected
}
}
|
Applicability
Mistakes regarding precedence guidelines can cause an expression to be evaluated in an unintended way. This can lead to unexpected and abnormal program behavior.
EXP53-EX0: Parentheses may be omitted from mathematical expressions that follow the algebraic precedence rules. For instance, consider the expression:
...
Code Block | ||
---|---|---|
| ||
x + (y * z) |
Risk Assessment
Mistakes regarding precedence guidelines can cause an expression to be evaluated in an unintended way. This can lead to unexpected and abnormal program behavior.
...
Guideline
...
Severity
...
Likelihood
...
Remediation Cost
...
Priority
...
Level
...
EXP53-JG
...
low
...
probable
...
medium
...
...
L3
...
Detection
...
Detection of all expressions using low-precedence operators without parentheses is straightforward. Determining the correctness of such uses is infeasible in the general case; heuristic warnings could be useful.
...
C Coding Standard: EXP00-C. Use parentheses for precedence of operation
C++ Secure Coding Standard: EXP00-CPP. Use parentheses for precedence of operation
Bibliography
[ESA 2005] | Rule 65: Use parentheses to explicitly indicate the order of execution of numerical operators |
| |
Rule 77: Clarify the order of operations with parentheses |
...