2 Expressions
This chapter covers
- Precedence-related errors
- Common mistakes when one operator is used instead of another
- Pitfalls when using a conditional expression
- Mistakes with method calls and method references
This chapter discusses the common bugs that are localized inside the single Java expression, such as using a wrong operator or assuming wrong operator precedence. Such bugs may result in unexpected resulting value of the expression. I will also briefly discuss the bugs when expression value is calculated correctly but ignored.
I don’t discuss here bugs related to specific data types like numbers, strings or collections. These are covered in subsequent chapters.
2.1 Mistake #1. Wrong precedence in arithmetic expressions
Many programming languages, including Java, provide a number of operators that have different priorities, which affect the order of expression evaluation. The precedence can be changed using parentheses. Some priorities are pretty natural, and rarely cause mistakes. For example, we all know from school that the multiplication and division operations have higher precedence than addition and subtraction. Java follows the same convention, so no surprises there.
2.1.1 Bitwise operators
Problems start to appear if you use more exotic operators, notably ones that manipulate with bits. For example, consider the following code sample:
int updateBits(int bits) {
return bits & 0xFF00 + 1;
}