3.2 Unary Operators
These are operators that have only a single operand. They include the sign operators, increment/decrement operators, and the logical NOT operator.
1. Increment/Decrement Operators (++, --)
Among the most frequently used unary operators, they increase or decrease the value of the operand by 1. They are mostly used in loops.
- Increment Operator (
++): Increases the operand's value by 1. - Decrement Operator (
--): Decreases the operand's value by 1.
Prefix and Postfix
The time at which the expression is evaluated depends on whether the operator is placed before or after the operand. (There is no difference when used standalone).
int i = 5, j = 0;
j = i++; // Postfix: i's value (5) is assigned to j first, then i is increased by 1
// Result: i = 6, j = 5
int x = 5, y = 0;
y = ++x; // Prefix: x is increased by 1 first, then that value (6) is assigned to y
// Result: x = 6, y = 6
2. Sign Operators (+, -)
They are identical to signs in mathematics. The - operator returns the result of reversing the operand's sign. The + operator effectively does nothing and is rarely used.
int i = -10;
i = -i; // i's value is reversed, becoming +10.
Note: Sign operators can only be used with primitive types, excluding boolean and char types.
3. Logical NOT Operator (!)
It changes true to false, and false to true. It holds the same meaning as placing 'NOT' in front of a word. It can only be used with the boolean type.
boolean power = false;
System.out.println(!power); // Outputs true
power = !power; // Utilized when toggling a value
It is primarily used in conditional or control statements to reverse the logic and the outcome of a conditional expression.