Unary Operators in Java:
Unary operators operate on a single operand.
They are commonly used to increment/decrement values, negate numbers, or reverse boolean logic.
List of Unary Operators
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
| + | Unary plus | Indicates a positive value (usually skipped) | +a | +5 if a=5 |
| - | Unary minus | Negates the value | -a | -5 if a=5 |
| ++ | Increment | Increases value by 1 | ++a or a++ | a = a + 1 |
| -- | Decrement | Decreases value by 1 | --a or a-- | a = a - 1 |
| ! | Logical NOT | Reverses a boolean value | !true | false |
Notes:
- Unary operators work with one operand only.
- ++ and -- have two forms:
- Prefix (++a): Increments before use.
- Postfix (a++): Increments after use.
- ! is used to negate boolean conditions, especially in if, while, and logical checks.
Example:
class ShikshaSanchar {
public static void main(String[] args) {
int a = 5;
boolean isJavaFun = true;
System.out.println("+a: " + (+a)); // Unary plus
System.out.println("-a: " + (-a)); // Unary minus
System.out.println("a++: " + (a++)); // Post-increment
System.out.println("After a++: " + a); // Value after increment
System.out.println("++a: " + (++a)); // Pre-increment
System.out.println("--a: " + (--a)); // Pre-decrement
System.out.println("!isJavaFun: " + (!isJavaFun)); // Logical NOT
}
}
Output:
+a: 5
-a: -5
a++: 5
After a++: 6
++a: 7
--a: 6
!isJavaFun: false
Explanation:
- +a → Just gives the positive value.
- -a → Negates the number.
- a++ → Returns 5, then makes a = 6.
- ++a → Makes a = 7, then returns 7.
- --a → Decreases to 6.
- !isJavaFun → Reverses true to false.
Special Examples – Pre/Post Increment & Decrement with Assignment
1. i = i++
int i = 5;
i = i++;
System.out.println(i); // Output: 5
Explanation:
- i++ returns 5, then increments i to 6.
- But i = 5 reassigns the old value.
- Final value: i = 5
2. j = ++j
int j = 5;
j = ++j;
System.out.println(j); // Output: 6
Explanation:
- ++j increments first, becomes 6.
- Then 6 is assigned to j.
- Final value: j = 6
3. x = x--
int x = 5;
x = x--;
System.out.println(x); // Output: 5
Explanation:
- x-- returns 5, then decrements x to 4.
- But x = 5 reassigns the old value.
- Final value: x = 5
4. y = --y
int y = 5;
y = --y;
System.out.println(y); // Output: 4
Explanation:
- --y decrements first to 4,
- then assigns 4 to y.
- Final value: y = 4
Summary:
- Unary operators are simple but powerful tools in Java.
- Useful in loops, conditions, counters, and boolean checks.
- Know the difference between prefix and postfix ++ and – with their working.
- ! is essential for negating conditions in if, while, etc.