Increment/Decrement Unary Operators
The beauty of unary operators is that, they require only single operand to get the same result as compare to the arithmetic operators; they perform various operations such as increment(++)/decrement(–) a value by one, negating an expression, or inverting the value of a boolean.
Operator | Description |
---|---|
++ | Increment operator; increments a value by 1 |
— | Decrement operator; decrements a value by 1 |
Prefix & Postfix
(++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value
Main.java
public class Main{
public static void main(String[] args){
int i = 3;
System.out.println(i); // prints 3
System.out.println(i++); // prints 3 but not 4
System.out.println(++i); //print 5
}
}
Output
3
3
5