Unary Operators
Unary operators work on a single value (unlike most operators, which need two). Common examples include increment (++), decrement (--), and unary minus (-) for making a number negative.
1. What are Unary Operators?
Unary operators work on a single value (unlike most operators, which need two). Common examples include increment (++), decrement (--), and unary minus (-) for making a number negative.
2. Why is it used?
Unary operators are extremely common for counting purposes — like increasing a counter by 1 every time a loop runs, without writing a longer expression each time.
3. Real-Life Example
Think of a movie theatre's ticket counter that increases by one every time a new customer buys a ticket. Instead of manually recalculating, the counter simply increases by one step — just like counter++ in Java.
4. Syntax
javaa++; // increases a by 1 (post-increment) ++a; // increases a by 1 (pre-increment) a--; // decreases a by 1 -a; // makes a value negative
5. Example Program
javapublic class UnaryDemo { public static void main(String[] args) { int count = 5; count++; System.out.println("After increment: " + count); count--; System.out.println("After decrement: " + count); } }
Output:
After increment: 6
After decrement: 56. Key Points to Remember
a++(post-increment) uses the current value first, then increases it;++a(pre-increment) increases it first, then uses the new value.- This difference between pre- and post- versions is a frequent interview question.
- Unary minus (
-a) simply reverses the sign of a number.