Unary operator in Java
Unary operators in Java act on a single operand, unlike binary operators that require two. They are used for tasks like incrementing values, negating numbers, and inverting boolean expressions.
Unary Plus (+)
Indicates a positive value. It rarely changes behavior since numbers are positive by default, but it can be used for clarity or type promotion.
int a = +5; // same as 5
Unary Minus (-)
Negates the value of an expression, flipping a positive number to negative and vice versa.
int a = 5;
int b = -a; // b = -5
Increment Operator (++)
Increases the value of a variable by 1. It comes in two forms: pre-increment (++x), which increments before using the value, and post-increment (x++), which uses the value first, then increments.
int x = 5;
System.out.println(++x); // 6, incremented first
System.out.println(x++); // 6, then becomes 7
Decrement Operator (--)
Decreases the value of a variable by 1, and similarly comes in pre-decrement (--x) and post-decrement (x--) forms.
int y = 5;
System.out.println(--y); // 4, decremented first
System.out.println(y--); // 4, then becomes 3
Logical NOT (!)
Inverts a boolean value — turning true into false and false into true.
boolean isReady = false;
System.out.println(!isReady); // true
+— unary plus, indicates a positive value-— unary minus, negates a value++— increment, increases a value by 1--— decrement, decreases a value by 1!— logical NOT, inverts a boolean
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.