Understanding Java’s operators
Operators can be grouped into the following categories:
- Unary operators
- Arithmetic operators
- Relational operators
- Logical operators
- Ternary operator
- Compound assignment operators
We will now discuss each category in turn.
Unary operators
Unary operators have only one operand, hence the term unary. Let’s examine them.
Prefix and postfix unary operators
++
and --
denote these operators and they increment and decrement by 1, respectively. If the operator appears before the variable, it is known as prefix, while if the operator appears after the variable, it is called postfix. For example, ++x is prefix increment, whereas y-- is postfix decrement.
Depending on whether ++
or --
appears before or after the variable can, in some situations, affect the overall expression. This is best explained with a code sample, as shown in Figure 3.1:
Figure 3.1 – Prefix and postfix...