Unary Operators in Java
In this class, We discuss Unary Operators in Java.
The reader should have prior knowledge of arithmetic and logical operators. Click Here.
1) Postfix ++ and —
2) Prefix ++, –, -, ~, !
Example:
a=5;
System.out.println(a++);
System.out.println(a);
We write the ++ operator after the variable a. We call postfix increment.
First, the value of a is assigned then a is incremented.
The first display statement output is 5.
The second display statement will output 6.
Example 2:
a=5 b=6 c
c= a++ + b
System.out.println(c) will display 11
System.out.println(a) will display 6
Similarly, a– will decrement the value, i.e., a=a-1
Prefix increment
First, increment the value, then assign the value.
a=5 b=6 c
c= ++a + b
System.out.println(c) will display 12
System.out.println(a) will display 6
Unary Minus:
a= -2
The minus sign shown before two will give a negative 2.
Example 3:
a = 20 b = 10 c
c = -a + b
-a will take value -20.
System.out.println(c) will display -10.
Bitwise complement:
a=5, b
b = ~a;
System.out.println(b) will output -6.
5 in binary 000101
the bitwise complement will change the bit values from 1 to 0 and vice versa.
~a = 111010 is equal to -6 using a twos-complement representation.
Logical Not!
boolean x = true;
System.out.println(!x) will output false.