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. Table 2.1 shows the operator precedence in Java.
Table 2.1 Operator precedence in Java
| Precedence |
Operators |
| 1 |
Postfix operators: ++, -- |
| 2 |
Prefix operators: ++, --, +, -, ~, ! |
| 3 |
Multiplicative: *, /, % |
| 4 |
Additive: +, - |
| 5 |
Shift: <<, >>, >>> |
| 6 |
Relational: <, >, <=, >=, instanceof |
| 7 |
Equality: ==, != |
| 8 |
Bitwise & |
| 9 |
Bitwise ^ |
| 10 |
Bitwise | |
| 11 |
Logical && |
| 12 |
Logical || |
| 13 |
Conditional ?: |
| 14 |
Assignment: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>= |