Thursday, December 26, 2024
Google search engine
HomeLanguagesJavaJava Unary Operator with Examples

Java Unary Operator with Examples

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-- = 5 // 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 = 5 //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);
 
        // fro user inputs here is the code.
 
        // System.out.print("Enter a number: ");
        // int num = sc.nextInt();
        int num = 10;
 
        int result = +num;
        System.out.println(
            "The value of result after unary plus is: "
            + result);
 
        result = -num;
        System.out.println(
            "The value of result after unary minus is: "
            + result);
 
        result = ++num;
        System.out.println(
            "The value of result after pre-increment is: "
            + result);
 
        result = num++;
        System.out.println(
            "The value of result after post-increment is: "
            + result);
 
        result = --num;
        System.out.println(
            "The value of result after pre-decrement is: "
            + result);
 
        result = num--;
        System.out.println(
            "The value of result after post-decrement is: "
            + result);
    }
}


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 result after pre-decrement is: 11
The value of result after post-decrement is: 11

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.

Adavantages 

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.

RELATED ARTICLES

Most Popular

Recent Comments