The Wayback Machine - https://web.archive.org/web/20241008230911/https://www.geeksforgeeks.org/java-unary-operator-with-examples/
Open In App

Java Unary Operator with Examples

Last Updated : 29 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types:

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators

Unary Operators in Java

Java unary operators are the types that need only one operand to perform any operation like increment, decrement, negation, etc. It consists of various arithmetic, logical and other operators that operate on a single operand. Let’s look at the various unary operators in detail and see how they operate. 

Operator 1: Unary minus(-)

This operator can be used to convert a positive value to a negative one. 

Syntax: 

-(operand)

Illustration: 

a = -10

Example:

Java
// Java Program to Illustrate Unary - Operator

// Importing required classes
import java.io.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Declaring a custom variable
        int n1 = 20;

        // Printing the above variable
        System.out.println("Number = " + n1);

        // Performing unary operation
        n1 = -n1;

        // Printing the above result number
        // after unary operation
        System.out.println("Result = " + n1);
    }
}

Output
Number = 20
Result = -20

Operator 2: ‘NOT’ Operator(!)

This is used to convert true to false or vice versa. Basically, it reverses the logical state of an operand.

Syntax: 

!(operand)

Illustration: 

cond = !true;
// cond < false

Example:

Java
// Java Program to Illustrate Unary NOT Operator

// Importing required classes
import java.io.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Initializing variables
        boolean cond = true;
        int a = 10, b = 1;

        // Displaying values stored in above variables
        System.out.println("Cond is: " + cond);
        System.out.println("Var1 = " + a);
        System.out.println("Var2 = " + b);

        // Displaying values stored in above variables
        // after applying unary NOT operator
        System.out.println("Now cond is: " + !cond);
        System.out.println("!(a < b) = " + !(a < b));
        System.out.println("!(a > b) = " + !(a > b));
    }
}

Output
Cond is: true
Var1 = 10
Var2 = 1
Now cond is: false
!(a < b) = true
!(a > b) = false

Operator 3: Increment(++)

It is used to increment the value of an integer. It can be used in two separate ways: 

3.1: Post-increment operator

When placed after the variable name, the value of the operand is incremented but the previous value is retained temporarily until the execution of this statement and it gets updated before the execution of the next statement. 

Syntax: 

num++

Illustration: 

num = 5
num++ = 6

3.2: Pre-increment operator

When placed before the variable name, the operand’s value is incremented instantly.

Syntax: 

++num

Illustration: 

num = 5
++num = 6

Operator 4: Decrement ( — )

It is used to decrement the value of an integer. It can be used in two separate ways: 

4.1: Post-decrement operator

When placed after the variable name, the value of the operand is decremented but the previous values is retained temporarily until the execution of this statement and it gets updated before the execution of the next statement. 

Syntax: 

num--

Illustration: 

num = 5
num-- = 4 // Value will be decremented before execution of next statement.

4.2: Pre-decrement operator

When placed before the variable name, the operand’s value is decremented instantly. 

Syntax: 

--num

Illustration:

num = 5
--num = 4 //output is 5, value is decremented before execution of next statement

Operator 5: Bitwise Complement(~)

This unary operator returns the one’s complement representation of the input value or operand, i.e, with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. 

Syntax: 

~(operand)

Illustration: 

a = 5 [0101 in Binary]
result = ~5
This performs a bitwise complement of 5
~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6

Example:

Java
// Java program to Illustrate Unary
// Bitwise Complement Operator

// Importing required classes
import java.io.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Declaring a variable
        int n1 = 6, n2 = -2;

        // Printing numbers on console
        System.out.println("First Number = " + n1);
        System.out.println("Second Number = " + n2);

        // Printing numbers on console after
        // performing bitwise complement
        System.out.println(
            n1 + "'s bitwise complement = " + ~n1);
        System.out.println(
            n2 + "'s bitwise complement = " + ~n2);
    }
}

Output
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1

Example program in Java that implements all basic unary operators for user input:

Java
import java.util.Scanner;

public class UnaryOperators {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Uncomment this block for user input
        // System.out.print("Enter a number: ");
        // int num = sc.nextInt();
        
        // Initialize num
        int num = 10;

        // Unary plus
        int result = +num;
        System.out.println("The value of result after unary plus is: " + result);

        // Unary minus
        result = -num;
        System.out.println("The value of result after unary minus is: " + result);

        // Pre-increment
        result = ++num;
        System.out.println("The value of result after pre-increment is: " + result);

        // Post-increment
        result = num++;
        System.out.println("The value of result after post-increment is: " + result);

        // Pre-decrement
        result = --num;
        System.out.println("The value of result after pre-decrement is: " + result);

        // Post-decrement
        result = num--;
        System.out.println("The value of result after post-decrement is: " + result);

        // Close the scanner
        sc.close();
    }
}

Output
The value of result after unary plus is: 10
The value of result after unary minus is: -10
The value of result after pre-increment is: 11
The value of result after post-increment is: 11
The value of re...

Explanation: 

The above program implements all basic unary operators in Java using user input. The program uses the Scanner class from the java.util package to read user input from the console. The following steps describe how the program works in detail:

  • Import the java.util.Scanner class: The program starts by importing the Scanner class, which is used to read input from the console.
  • Create a Scanner object: Next, a Scanner object sc is created and associated with the standard input stream System.in.
  • Read the number from the user: The program prompts the user to enter a number and uses the nextInt() method of the Scanner class to read the input. The input is stored in the num variable of type int.
  • Use unary plus operator: The program uses the unary plus operator + to perform a positive operation on num. The result of the operation is stored in the result variable of type int.
  • Use unary minus operator: The program uses the unary minus operator – to perform a negative operation on num. The result of the operation is stored in the result variable.
  • Use pre-increment operator: The program uses the pre-increment operator ++ to increment the value of num before using it in an expression. The result of the operation is stored in the result variable.
  • Use post-increment operator: The program uses the post-increment operator ++ to increment the value of num after using it in an expression. The result of the operation is stored in the result variable.
  • Use pre-decrement operator: The program uses the pre-decrement operator — to decrement the value of num before using it in an expression. The result of the operation is stored in the result variable.
  • Use post-decrement operator: The program uses the post-decrement operator — to decrement the value of num after using it in an expression. The result of the operation is stored in the result variable.
  • Print the results: The program prints out the final values of result using the println method of the System.out object after each operation.
  • This program demonstrates how to use basic unary operators in Java. The Scanner class makes it easy to read user input from the console, and various unary operators are used to modify the value of the num variable in the program.

Advantages 

The main advantage of using unary operators in Java is that they provide a simple and efficient way to modify the value of a variable. Some specific advantages of using unary operators are:

  1. Concise and Easy to Use: Unary operators are simple to use and require only one operand. They are easy to understand and make code more readable and concise.
  2. Faster than Other Operators: Unary operators are faster than other operators as they only require one operand. This makes them ideal for operations that need to be performed quickly, such as incrementing a counter.
  3. Pre- and Post-Increment/Decrement: Unary operators provide both pre- and post-increment and decrement options, which makes them useful for a variety of use cases. For example, the pre-increment operator can be used to increment the value of a variable before using it in an expression, while the post-increment operator can be used to increment the value of a variable after using it in an expression.
  4. Modifying Primitive Types: Unary operators can be used to modify the value of primitive types such as int, long, float, double, etc.

Overall, unary operators provide a simple and efficient way to perform operations on variables in Java, and they can be used in a variety of scenarios to make code more readable and concise.



Previous Article
Next Article

Similar Reads

&& operator in Java with Examples
&& is a type of Logical Operator and is read as "AND AND" or "Logical AND". This operator is used to perform "logical AND" operation, i.e. the function similar to AND gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensiv
1 min read
& Operator in Java with Examples
The & operator in Java has two definite functions: As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false. However, there is a slight difference between them, which h
2 min read
Diamond operator for Anonymous Inner Class with Examples in Java
Prerequisite: Anonymous Inner Class Diamond Operator: Diamond operator was introduced in Java 7 as a new feature.The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable. The diamond operator could not be used with Anonymous inn
2 min read
Java Ternary Operator with Examples
Operators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic OperatorsUnar
4 min read
Double colon (::) operator in Java
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate t
4 min read
Difference between concat() and + operator in Java
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Concatenation is the process of joining end-
6 min read
|| operator in Java
|| is a type of Logical Operator and is read as "OR OR" or "Logical OR". This operator is used to perform "logical OR" operation, i.e. the function similar to OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is true, i.e. it has a short-circuiting effect. Used extensively to test fo
1 min read
Shift Operator in Java
Operators in Java are used to performing operations on variables and values. Examples of operators: +, -, *, /, >>, <<. Types of operators: Arithmetic Operator,Shift Operator,Relational Operator,Bitwise Operator,Logical Operator,Ternary Operator andAssignment Operator. In this article, we will mainly focus on the Shift Operators in Java
4 min read
Left Shift Operator in Java
The decimal representation of a number is a base-10 number system having only ten states 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. For example, 4, 10, 16, etc. The Binary representation of a number is a base-2 number system having only two states 0 and 1. For example, the binary representation of 4, a base-9 decimal number system is given by 100, 10 as 101
4 min read
Addition and Concatenation Using + Operator in Java
Till now in Java, we were playing with the integral part where we witnessed that the + operator behaves the same way as it was supposed to because the decimal system was getting added up deep down at binary level and the resultant binary number is thrown up at console in the generic decimal system. But geeks even wondered what if we play this + ope
2 min read
new Operator vs newInstance() Method in Java
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.In general, the new operator is u
3 min read
instanceof operator vs isInstance() Method in Java
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator. The isInstance method is equivalent to instanceof operator. The method is
3 min read
new operator in Java
When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process : Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is sim
5 min read
Java Ternary Operator Puzzle
Find the output of the program public class GFG { public static void main(String[] args) { char x = 'X'; int i = 0; System.out.print(true ? x : 0); System.out.print(false ? i : x); } } Solution: If you run the program,you found that it prints X88. The first print statement prints X and the second prints 88. The rules for determining the result type
2 min read
dot(.) Operator in Java
The dot (.) operator is one of the most frequently used operators in Java. It is essential for accessing members of classes and objects, such as methods, fields, and inner classes. This article provides an in-depth look at the dot operator, its uses, and its importance in Java programming. Dot(.) Operator in Java The dot operator is used to access
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java Clock tickMinutes() method in Java with Examples
java.time.Clock.tickMinutes(ZoneId zone) method is a static method of Clock class that returns the current instant ticking in whole minutes using the best available system clock and the time-zone of that instant is same as the time-zone passed as a parameter. Nanosecond and second fields of the clock are set to zero to round the instant in the whol
3 min read
Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is
3 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Article Tags :
Practice Tags :