In this tutorial you will learn about the Java Unary Operators and its application with practical example.
Java Unary Operators (post and pre)
In Java, ++ and — are known as increment and decrement operators respectively. These are unary operators which means they work on a single operand. ++ adds 1 to operand and — subtracts 1 to operand respectively. When ++ is used as prefix(like: ++i), ++i will increment the value of i and then return it but, if ++ is used as postfix(like: i++), operator will return the value of operand first and then only increment it.
Operator | Example | Description |
---|---|---|
++ [prefix] | ++a | The value of an increment |
++ [postfix] | a++ | The value of a before the increment |
— [prefix] | –a | The value of an after decrement |
— [postfix] | a– | The value of a before the decrement |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Main { public static void main(String[] args) { int x=10; System.out.println("W3Adda - Java Unary Operators"); System.out.println(x++);//10 (11) System.out.println(++x);//12 System.out.println(x--);//12 (11) System.out.println(--x);//10 } } |
When you run the above java program, you will see the following output.
Output:-