Home | Computer Science
Operators
Definition
Unary operators in Java are operators that operate on a single operand. They are used to increment, decrement, negate, or invert a value.
Unary Operators
Common unary operators are:
- + : Indicates a positive value (typically not used as it's implied).
- - : Negates a value, converting positive to negative or vice versa.
- ++ : Increments a value by 1 (both pre-increment and post-increment).
- -- : Decrements a value by 1 (both pre-decrement and post-decrement).
Syntax Example:
- num++; // Post-increment, num becomes 6
- ++num; // Pre-increment, num becomes 7
- num--; // Post-decrement, num becomes 6
- --num; // Pre-decrement, num becomes 5
Program
INPUT
public class UnaryOperatorsExample {
public static void main(String[] args) {
int num = 5;
// Post-increment
System.out.println("Post-increment (num++): " + (num++)); // Displays 5, then num becomes 6
// Pre-increment
System.out.println("Pre-increment (++num): " + (++num)); // num becomes 7, then displays 7
// Post-decrement
System.out.println("Post-decrement (num--): " + (num--)); // Displays 7, then num becomes 6
// Pre-decrement
System.out.println("Pre-decrement (--num): " + (--num)); // num becomes 5, then displays 5
}
}
OUTPUT