Understanding Unary Operator in Java

Understanding Unary Operator in Java

5 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 15, 2024 12:27 IST

Have you ever wondered how unary operators work in Java? These operators, requiring only one operand, are fundamental in various programming scenarios. They include increment (++), decrement (--), and logical NOT (!), each performing distinct operations like altering a variable's value or inverting a boolean expression. Let's understand more!

Operators in Java are special symbols or keywords that are used to perform operations on variables and values. These operations can range from basic mathematical calculations to complex logical comparisons. Operators in Java are categorized into several types based on their functionality. In this blog, we will learn about one of its types in detail, which is the unary operators!

Check out Java Courses Here!

Table of Content

 
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

โ€“ / โ€“
350 hours
Free
6 months
โ€“ / โ€“
4 months
โ€“ / โ€“
โ€“ / โ€“
โ€“ / โ€“
1 month
โ‚น40 K
7 weeks
โ‚น7.8 K
3 months
โ‚น8.47 K
2 months
โ‚น7 K
6 months
โ‚น4 K
2 months

What is a Unary Operator in Java?

A unary operator in Java is an operator that operates on only one operand. Unary operators are used to perform various operations, such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. Unary operators are integral in many programming languages and are used to write concise and efficient code, especially in scenarios involving arithmetic operations, boolean logic, and low-level bit manipulation.

Types and Syntax of Unary Operators

Operator Type

Symbol

Syntax Example

Use Case

Notes

Unary Plus

+

+x

Emphasize a positive number

Rarely used as numbers are positive by default

Unary Minus

-

-x

Negate a number

Inverts the sign of a number

Increment

++

x++ or ++x

Increase a value by one

x++ is post-increment, ++x is pre-increment

Decrement

--

x-- or --x

Decrease a value by one

x-- is post-decrement, --x is pre-decrement

Logical NOT

!

!x

Invert a boolean value

Converts true to false and vice versa

Bitwise Complement

~

~x

Invert each bit of an integer value

Used for bit manipulation

Points to be noted

  • Pre vs. Post Increment/Decrement: The pre-increment/decrement operators (++x, --x) modify the value of x before it's used in an expression, whereas the post-increment/decrement operators (x++, x--) modify the value after it's been used in the expression.
  • Type Casting: While not a traditional unary operator, type casting (e.g. (int) 3.14) is an important unary operation in Java, used to convert a value from one data type to another.
  • Operator Overloading: Java does not support operator overloading, so the behaviour of these unary operators is consistent and cannot be changed for different data types or objects.
  • Bitwise Complement: The bitwise complement operator ~ is less commonly used than the other unary operators and is primarily relevant in low-level programming or for specific algorithmic purposes.
  • Effect on Original Variable: Increment and decrement operators (++, --) modify the value of the variable they are applied to, while other unary operators do not change the original variable's value.

Java String Compare: A Guide to Effective String Comparison in Java

What are Identifiers in Java?

Getting Started with Java Hello World Program

All About Assignment Operator in Java

Examples Showing Usage of Unary Operator

Example 1: User Input Toggle

Problem Statement: A program where the user can input a boolean value (true or false) to represent the visibility of an element. The program then toggles this visibility.


 
import java.util.Scanner;
public class ToggleVisibility {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter visibility (true/false): ");
boolean isVisible = scanner.nextBoolean(); // User input for visibility
// Toggle visibility
isVisible = !isVisible;
System.out.println("Toggled Visibility: " + isVisible);
}
}
Copy code

Output

Enter visibility (true/false): 
true
Toggled Visibility: false

Example 2: User Input for Calculating Debt

Problem Statement: A program that takes the user's initial debt and the payment amount as input and then calculates the remaining debt.


 
import java.util.Scanner;
public class CalculateDebt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter initial debt: ");
int debt = scanner.nextInt(); // User input for debt
System.out.println("Enter payment made: ");
int payment = scanner.nextInt(); // User input for payment
debt += -payment; // Decrease debt by payment amount
System.out.println("Remaining Debt: " + debt);
}
}
Copy code

Output

Enter initial debt: 
1000
Enter payment made: 
200
Remaining Debt: 800

Example 3: User-Controlled Increment

Problem Statement: Create a program where the user can input a starting number and then increment it by 1 as many times as they desire.


 
import java.util.Scanner;
public class UserIncrement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting number: ");
int number = scanner.nextInt(); // User input for starting number
System.out.println("How many times do you want to increment this number?");
int increments = scanner.nextInt(); // User input for increments
for (int i = 0; i < increments; i++) {
number++; // Increment number each time
}
System.out.println("Final number after increments: " + number);
}
}
Copy code

Output

Enter a starting number: 
7
How many times do you want to increment this number?
9
Final number after increments: 16

Example 4: User Input for Bitwise Complement

Problem Statement: A program where the user inputs an integer, and the program outputs its bitwise complement.


 
import java.util.Scanner;
public class BitwiseComplement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = scanner.nextInt(); // User input for an integer
int complement = ~number; // Applying bitwise complement
System.out.println("Bitwise complement of " + number + " is: " + complement);
}
}
Copy code

Output

Enter an integer: -8
Bitwise complement of -8 is: 7

Array Programs in Java | Beginner to Expert Level

A Guide to Power Function in Java

Java Comments | About, Types and Examples

Let's Learn Logical Operators in Java

All About Arithmetic Operators in Java

Mastering Bitwise Operator in Java

Conclusion

Thus, unary operators in Java play a crucial role in simplifying code and enhancing readability, especially when performing single-operand operations. These operators, including increment (++), decrement (--), unary minus (-), unary plus (+), logical NOT (!), and bitwise complement (~), are essential tools in a Java programmer's toolkit.

FAQs

What are Unary Operators in Java?

Unary operators in Java are operators that perform operations on a single operand, which is usually a single value or variable. They can be used to increment, decrement, negate, or manipulate the value of the operand.

What are the Common Unary Operators in Java?

Some common unary operators in Java include:

  • ++ (Increment): Increases the value of a variable by 1.
  • -- (Decrement): Decreases the value of a variable by 1.
  • + (Positive): Indicates a positive value (rarely used).
  • - (Negation): Negates the value of a variable or expression.
  • ! (Logical NOT): Inverts the boolean value of a boolean expression.

How Do Prefix and Postfix Increment/Decrement Operators Differ?

Prefix increment (++x) and decrement (--x) operators increase or decrease the value of a variable before its current value is used in an expression. Postfix increment (x++) and decrement (x--) operators first use the current value and then increment or decrement it.

Can Unary Operators Be Applied to Non-Numeric Types?

Unary operators like + and - can be applied to non-numeric types, but their usage is limited. For example, using - with a non-numeric type may result in a compilation error.

What Are the Use Cases for the Logical NOT Operator !?

The ! (logical NOT) operator is primarily used to negate boolean expressions. It's often used in conditions to reverse the truth value of a boolean variable or expression. For example, if (!isReady) checks if isReady is false.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio