Unary operators in Java work on a single operand. They are commonly used to increment, decrement, negate values, or reverse boolean results.
+ Unary plus- Unary minus++ Increment-- Decrement! Logical NOT
// Demonstrating Java unary operators
class UnaryDemo {
public static void main(String[] args) {
int a = 10;
System.out.println(+a);
System.out.println(-a);
System.out.println(++a);
System.out.println(--a);
boolean flag = false;
System.out.println(!flag);
}
}
Unary plus prints the value as-is, unary minus negates it, increment and decrement change the value by one, and logical NOT reverses the boolean value.
Click the buttons to visualize the difference between prefix and postfix operators.
a and observe the output