chapter two

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;
}

2.1.2 Binary shift

2.2 Mistake #2. Lack of parentheses in conditions

2.2.1 && and || precedence

2.2.2 Conditional operator and addition

2.2.3 Conditional operator and null check

2.2.4 Initial capacity

2.2.5 Conditional operator returning a boolean value

2.3 Mistake #3. Accidental concatenation instead of addition

2.4 Mistake #4. Multiline string literals

2.5 Mistake #5. Unary plus

2.6 Mistake #6. Implicit type conversion in conditional expression

2.6.1 Boxed numbers in conditional expressions

2.6.2 Nested conditional expressions

2.7 Mistake #7. Using non-short-circuit logic operators

2.8 Mistake #8. Mixing && and ||

2.9 Mistake #9. Incorrect use of variable arity calls

2.15 Summary