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 can , which also improves code readability. The precedence of operations by the order of the subclauses are defined in the Java Tutorials [Tutorials 2008].
...
This expression gets evaluated as follows, resulting in the value 0.:
Code Block |
---|
x & (1337 - 1337) |
...
This compliant solution uses parentheses to ensure that the expression evaluates as intended.:
Code Block | ||
---|---|---|
| ||
public static final int MASK = 1337; public static final int OFFSET = -1337; public static int computeCode(int x) { return (x & MASK) + OFFSET; } |
...
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" } } |
...
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 } } |
...
Parentheses may be omitted from mathematical expressions that follow the algebraic precedence rules. For instance, consider the following expression:
Code Block |
---|
x + y * z |
...
Related Guidelines
[Rogue 2000] | Rule 77: , Clarify the order of operations with parentheses |
Bibliography
[ESA 2005] | Rule 65: , Use parentheses to explicitly indicate the order of execution of numerical operators |
...
...