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

 

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
Java String Compare: A Guide to Effective String Comparison in Java
Have you ever wondered how to compare strings in Java? You can use various methods for that, like using equals(), using == Operator, using equalsIgnoreCase(), using compareTo() and using compareToIgnoreCase()....read more

What are Identifiers in Java?
What are Identifiers in Java?
Have you ever wondered how Java keeps everything organized and accessible? It's all because of identifiers. Those unique labels assigned to variables, methods, and classes. These crucial elements of Java...read more

Getting Started with Java Hello World Program
Getting Started with Java Hello World Program
Do you know the significance of the "Hello World" program in Java? It's the first step for many into the world of programming, serving as a simple yet profound introduction...read more

All About Assignment Operator in Java
All About Assignment Operator in Java
Have you ever wondered how assignment operators function in Java? They are special symbols used for assigning values to variables, with the most basic one being the equal sign (=)....read more

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
Array Programs in Java | Beginner to Expert Level
Array programs in Java traverse from basic single-dimensional arrays to complex multi-dimensional arrays and dynamic arrays using ArrayList. From initializing and accessing array elements, to advanced operations like sorting and...read more

A Guide to Power Function in Java
A Guide to Power Function in Java
Have you ever wondered how mathematical power functions are implemented in programming languages like Java? In Java, the Math.pow() function is a powerful tool used to raise a number to...read more

Java Comments | About, Types and Examples
Java Comments | About, Types and Examples
Do you know what makes the code more readable? Comments, as they provide valuable context and explanations about the code, making it easier for both the original developers and others...read more

Let's Learn Logical Operators in Java
Let's Learn Logical Operators in Java
Have you ever wondered how logical operators in Java work? These operators, including AND (&&), OR (||), and NOT (!), are used to combine or invert boolean expressions, playing a...read more

All About Arithmetic Operators in Java
All About Arithmetic Operators in Java
Have you ever wondered how arithmetic operators in Java simplify mathematical calculations? Arithmetic operators in Java are simple yet powerful tools for performing numerical computations. Let's read more about it...read more

Mastering Bitwise Operator in Java
Mastering Bitwise Operator in Java
Have you ever wondered about the efficiency of low-level data manipulation in Java? Bitwise operators, like AND (&), OR (|), XOR (^), and shift operators (>, >>>), offer a powerful...read more

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