0% completed
Unary operators perform operations on a single operand. They can modify the operand's value or state directly. In Java, unary operators are used to increment or decrement numeric values, change the sign of a number, or invert a boolean value.
Operator | Description | Example |
---|---|---|
++ | Increment operator; increases an integer by 1 | a++ or ++a |
-- | Decrement operator; decreases an integer by 1 | a-- or --a |
+ | Unary plus; indicates a positive value (usually redundant) | +a |
- | Unary minus; negates the value of an expression | -a |
! | Logical complement; inverts the boolean value | !flag |
Below is an example that demonstrates the difference between post-increment and pre-increment operators.
Explanation:
int postIncrement = a++;
, the original value of a
(which is 5) is assigned to postIncrement
before a
is incremented to 6
.int preIncrement = ++a;
, a
is incremented first (from 6 to 7) and then the updated value is assigned to preIncrement
.Below is an example that demonstrates how to use the unary minus to negate a number and the logical complement operator to invert a boolean value.
Explanation:
int negatedNum = -num;
uses the unary minus to change the sign of num
, turning 10 into -10.boolean invertedFlag = !flag;
applies the logical complement, converting false
to true
.These examples illustrate how unary operators modify individual operands. Experiment with these operators to observe how they affect the values during runtime.
.....
.....
.....