What is Unary Operators in Java?
Unary operators in Java are operators that operate on a single operand to perform various operations, such as incrementing/decrementing a value, negating a boolean value, or inverting the sign of a number. Java provides several unary operators:
- Unary Plus (+)
- Unary Minus (–)
- Increment (++)
- Decrement (—)
- Logical NOT (!)
1. Unary Plus (+) #
The unary plus operator is used to indicate a positive value. Though it doesn’t change the value, it’s sometimes used for code readability.
Example:
public class UnaryOperatorExample {
public static void main(String[] args) {
int a = +5; // Positive value
System.out.println("a = " + a);
}
}
Output:
a = 5
2. Unary Minus (–) #
The unary minus operator negates the value of the operand, effectively changing its sign.
Example:
public class UnaryOperatorExample {
public static void main(String[] args) {
int a = 5;
int b = -a; // Negates the value of a
System.out.println("b = " + b);
}
}
Output:
b = -5
3. Increment (++) #
The increment operator increases the value of the operand by 1. It has two forms:
- Prefix Increment (++a): Increments the value before using it in an expression.
- Postfix Increment (a++): Uses the current value in an expression, then increments it.
Example:
public class UnaryOperatorExample {
public static void main(String[] args) {
int a = 5;
// Prefix: a is incremented to 6, then b is assigned 6
int b = ++a;
System.out.println("a = " + a + ", b = " + b);
int c = 5;
// Postfix: d is assigned 5, then c is incremented to 6
int d = c++;
System.out.println("c = " + c + ", d = " + d);
}
}
Output:
a = 6, b = 6
4. Decrement (—) #
The decrement operator decreases the value of the operand by 1. It also has two forms:
- Prefix Decrement (–a): Decrements the value before using it in an expression.
- Postfix Decrement (a–): Uses the current value in an expression, then decrements it.
Example:
public class UnaryOperatorExample {
public static void main(String[] args) {
int a = 5;
// Prefix: a is decremented to 4, then b is assigned 4
int b = --a;
System.out.println("a = " + a + ", b = " + b);
int c = 5;
// Postfix: d is assigned 5, then c is decremented to 4
int d = c--;
System.out.println("c = " + c + ", d = " + d);
}
}
Output:
a = 4, b = 4
c = 4, d = 5
5. Logical NOT (!) #
The logical NOT operator inverts the boolean value of the operand. If the operand is true, it becomes false, and vice versa.
Example:
public class UnaryOperatorExample {
public static void main(String[] args) {
boolean isTrue = true;
// Inverts the value of isTrue
boolean isFalse = !isTrue;
System.out.println("isTrue = " + isTrue);
System.out.println("isFalse = " + isFalse);
}
}
Output:
isTrue = true
isFalse = false
Summary #
Unary operators in Java are powerful tools for performing basic operations on single operands, such as changing signs, incrementing/decrementing values, or inverting booleans. They are essential for writing concise and efficient code in various programming scenarios.