Java - Unary Operators
Unary Operators in Java
Java unary operators need only one operand to perform any operation, and these operators modify the value of a variable based on the operation performed. These operators include increasing a value by 1, decreasing a value by 1, and negating an expression.
These operators work with numeric data types like int, float, double, and long. The most common unary operators are post-increment (x++) and post-decrement (x--), used for loop control.
List of Java Unary Operators
The following table lists the unary operators in Java:
| Name | Operator | Description | Example |
|---|---|---|---|
| Unary plus | + |
The unary plus operator indicates a positive value(numbers are positive without this, however). |
x = 5; y = +x; // y=5 |
| Unary minus | - | The unary minus operator can be used to convert a positive value to a negative value. | x = 5; y = -x; // y = -5(negates the value) |
| Increment | ++ | The increment operator increases the value by 1(pre-increment and post-increment). | x = 5; y = x++; // y = 5, x = 6 (post-increment) z = ++x; // pre-increment: x = 7, z = 7 |
| Decrement | -- | The decrement operator decreases the value by 1(pre-decrement and post-decrement). | x = 5; y = x--; // y = 5, x = 4 (post-decrement) z = --x; // pre-decrement: x = 3, z = 3 |
Unary Operators Examples
The following programs are simple examples that demonstrate the unary operators in Java:
Example 1
In this example, weâre creating a variable "x" with a value of 10. We've performed the unary plus and unary minus operations on "x" and printed the results:
public class Test {
public static void main(String args[]) {
int x = 10;
System.out.println("The value of +x = " + (+x));
System.out.println("The value of -x = " + (-x));
}
}
Output
The value of +x = 10 The value of -x = -10
Example 2
In this example, weâre creating a variable "x" with a value of 5. We've performed the post-increment and pre-increment operations on "x" and printed the results:
public class Test {
public static void main(String args[]) {
int x = 5;
System.out.println("The value of x++ = " + (x++));
System.out.println("The value of ++x = " + (++x));
}
}
Output
The value of x++ = 5 The value of ++x = 7
Example 3
In this example, weâre creating a variable "y" with a value of 5. We've performed the post-decrement and pre-decrement operations on "y" and printed the results:
public class Test {
public static void main(String args[]) {
int y = 5;
System.out.println("The value of y-- = " + (y--));
System.out.println("The value of --y = " + (--y));
}
}
Output
The value of y-- = 5 The value of --y = 3