Java Reference
In-Depth Information
public static int computeCode(int x) {
return (x & MASK) + OFFSET;
}
Noncompliant Code Example
In this noncompliant code example, the intent is to append either
"0"
or
"1"
to the string
"value="
.
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "1"
System.out.println("value=" + s == null ? 0 : 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 inten-
ded.
public class PrintValue {
public static void main(String[] args) {
String s = null;
// Prints "value=0" as expected
System.out.println("value=" + (s == null ? 0 : 1));
}
}
Applicability
Mistakes concerning precedence rules can cause an expression to be evaluated in an unin-
tended way, which can result in unexpected and abnormal program behavior.