2 Expressions

 

This chapter covers

  • Precedence-related errors
  • Common mistakes stemming from one operator being used instead of another
  • Pitfalls when using a conditional expression
  • Common problems when using method calls and method references

This chapter discusses common bugs localized inside the single Java expression, such as using an incorrect operator or assuming the wrong operator precedence. Such bugs may result in an unexpected value being produced by the expression. I will also briefly discuss the bugs caused by the expression value being calculated correctly but ignored.

This chapter does not cover bugs related to specific data types, like numbers, strings, or collections. These are covered in subsequent chapters.

2.1 Mistake 1: Incorrect assumptions about numeric operator precedence

Many programming languages, including Java, provide a number of operators with different priorities, each affecting the order of expression evaluation in different ways. The precedence can be changed using parentheses. Table 2.1 shows the operator precedence in Java.

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

2.1.1 Binary shift