Unary operators in Java are operators that operate on a single operand. They are used to perform various operations such as incrementing/decrementing a value, negating a value, or inverting the bits of a value. Here are the main unary operators in Java:
Unary Plus (
+
):- Indicates a positive value. While it doesn't change the sign of positive numbers, it can be used to emphasize the positive sign.
int x = 5;
int result = +x; // result is 5
Unary Minus (
-
):- Negates the value of its operand.
int y = 8;
int result = -y; // result is -8
- Increment (
++
):
Increases the value of its operand by 1.
int a = 3; a++; // a is now 4
There are two types of implement operators -
Post Increment: First initialise then increase.
Pre Increment: First increase then initialise.
For example -
Expression | Initial value of x | Value of y | Final value |
y = x++ | 10 | 10 | 11 |
y = ++x | 10 | 11 | 11 |
- Decrement (
--
):
Decreases the value of its operand by 1.
int b = 7; b--; // b is now 6
There are two types of implement operators -
Post Increment: First initialise then increase.
Pre Increment: First increase then initialise.
For example -
Expression | Initial value of x | Initial value of y | Final value |
y = x-- | 10 | 10 | 9 |
y = --x | 10 | 9 | 9 |
It's important to note that the increment and decrement operators can be used as a prefix (++a
or --a
) or a postfix (a++
or a--
). The difference between the two lies in when the increment or decrement is applied in relation to the surrounding expression.
- Logical Complement (
!
):
Inverts the logical state of its operand. If the operand is true, the result is false, and if the operand is false, the result is true.
This operator is only applicable for boolean.
boolean flag = true; boolean result = !flag; // result is false
Bitwise Complement (
~
):Inverts the bits of its operand, changing 1s to 0s and vice versa.
This operator is only applicable for integral not for boolean.
int number = 5; // binary: 0000 0000 0000 0000 0000 0000 0000 0101 int result = ~number; // binary: 1111 1111 1111 1111 1111 1111 1111 1010 (-6 in decimal)
Unary operators are essential in various programming scenarios, and they play a crucial role in expressions and statements. Understanding how these operators work is fundamental for writing efficient and correct Java code.