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. 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: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=

2.1.1 Bitwise operators

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.9.2 Mixing array and collection