Let’s learn unary operators in java.
Unary operators in java
Unary operator needs only one operand to increment, decrement, etc. Here are various unary operators,
- Logical complement operator (!): reverses logical state or value of operand. If the value is false, it converts value to true and vice versa.
- Unary minus (-): converts positive value to negative value.
- Increment (++): increments value of an integer. post and pre-increment.
- Decrement (- -): decrements value of an integer. post and pre-decrement.
- Unary plus (+): operator represents positive value. That is it makes all bits inverted, every 0 to 1 and every 1 to 0.
Here’s an example on ‘NOT’ (!) operator.
public class JavaUnaryOperator { public static void main(String[] args) { boolean bool = true; int a = 14, b = 5; System.out.println("Before using NOT operator(!): " + bool); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("After using using NOT operator(!): " + !bool); System.out.println("!(a < b) = " + !(a < b)); System.out.println("!(a > b) = " + !(a > b)); } }
Output:
Before using NOT operator(!): true
a = 14
b = 5
After using using NOT operator(!): false
!(a < b) = true !(a > b) = false
Here’s an example on unary minus operator(-).
public class JavaUnaryOperator { public static void main(String[] args) { int a = 5; System.out.println("Given number : " + a); a = -a; System.out.println("After using unary minus operator(-) : " + a); } }
Output:
Given number : 5
After using unary minus operator(-) : -5
Increment (++) operator increments value of an integer and this operator can be used in two ways post-increment and pre-increment.
Post-increment operator: If increment operator is placed after variable name, then value is first assigned and then incremented.
Example:
class JavaUnaryOperator { public static void main(String[] args) { int a = 6; int b = a++; System.out.println(b); } }
Output:
6
Pre-increment operator:
If increment operator is placed before variable name, then value is incremented first and then assigned.
Let’s see an example on pre-increment operator.
class JavaUnaryOperator { public static void main(String[] args) { int a = 6; int b = ++a; System.out.println(b); } }
Output:
7
Decrement operator(- -): decrements value of an integer and this operator in two ways post-decrement and pre-decrement.
Post-decrement operator: If decrement operator is placed after variable name, then value is first assigned and then decremented.
Example: a – –
class JavaUnaryOperator { public static void main(String[] args) { int a = 6; int b = a--; System.out.println(b); } }
Output:
6
Pre-decrement operator: If decrement operator is placed before variable name, then value is decremented first and then assigned.
Let’s see an example on pre-decrement operator.
class JavaUnaryOperator { public static void main(String[] args) { int a = 6; int b = --a; System.out.println(b); } }
Output:
5
Also read – inheritance in java