Unary operator in Java

Unary operator in Java

06 Sep 2024
Beginner
2.12K Views
17 min read

Unary Operators in Java: An Overview

We already discussed the Types of Operators in the previous tutorial. In this Java unary operator article, we'll explore the syntax, and types, providing a comprehensive overview with example of unary operator in Java. In Java, unary operators are essential components of the programming language that perform operations on a single operand.

To further enhance your understanding and application of unary operator's concepts, consider enrolling in the best Java Full Stack Developer Course, or Java Tutorial to gain knowledge about the effective utilization of unary operators for improved problem-solving and time management.

What are the Unary Operators in Java?

Unary operators are essential in Java programming because they allow developers to perform operations on a single operand with ease and efficiency. Unary operators are operators that perform operations on a single operand. In Java, there are several unary operators, each serving a distinct purpose. These operators can be applied to various data types, including numeric types, Boolean, and objects.

These operators are versatile and can be applied to various data types, including numeric types, Boolean, and objects.

Syntax of Unary Operator in Java:

The basic syntax for unary operators in Java is as follows:


result = unary_operator operand;

Here, the "unary_operator" is the unary operator being applied, and the "operand" is the value on which the operation is performed.

Read More - Top 50 Java Interview Questions For Freshers

Read More - Mostly Asked Java Multithreading Interview Questions

Types of Unary Operators

Java supports several unary operators, each serving a specific purpose. The primary unary operators are:

  1. Unary Plus Operator
  2. Unary Minus Operator
  3. Increment Operator
  4. Decrement Operator
  5. Logical Complement Operator

Types of Unary Operators

1. Unary Plus (+)

The unary plus operator is used to indicate a positive value. It does not change the sign of the operand.

Syntax


+operand;

Example

import java.io.*;
class UnaryOperator{
	public static void main(String[] args)
	{
		int num = 10;

		System.out.println("Before operation = " + num);
		num = +num;
		System.out.println("After operation = " + num);
	}
}  

Explanation

In this example, the unary plus operator is applied to num (num = +num;), which doesn't change the value but is included for illustrative purposes. Finally, the modified value of num is printed. The output of the program will display the original and modified values of the num variable.

Output

Before operation = 10
After operation = 10

2. Unary Minus (-)

The unary minus operator negates a numeric value, changing its sign.

Syntax


-operand;

Example

import java.io.*;
class UnaryOperator{
	public static void main(String[] args)
	{
		int num = 10;

		System.out.println("Before operation = " + num);
		num = -num;
		System.out.println("After operation = " + num);
	}
}

Explanation

In the above code in the Java Playground, initialize an integer variable num with the value 10, print its original value, and then apply the unary minus operator (-num) to change the sign of the variable. Finally, it prints the updated value of num. The output will display the original and modified values of num, illustrating the impact of the unary minus operation.

Output

Before operation = 10
After operation = -10

3. Increment Operator (++)

The increment operator is used to increase the value of a variable by 1. There are two forms of the increment operator:

  • Pre-increment Operator:

When the Pre-increment Operator is used before the variable name, the operand's value is quickly incremented.

Syntax


++variable;

Example

import java.io.*;

class UnaryOperator{
	public static void main(String[] args)
	{
		int num1 = 3;
                  int num2 = ++num1;
		System.out.println("After Pre-Increment = " + num2);
	}
}

Explanation

The example essentially demonstrates how the pre-increment operator modifies the value of the variable before using it in an assignment. In this case, it increments num1 by 1 and assigns the result to num2.

Output

After Pre-Increment = 4
  • Post-increment Operator:

When the Post-increment Operator is placed after the variable name, the operand's value is increased, but the previous value is maintained temporarily until the end of this statement and updated before the end of the next statement.

Syntax


variable++;

Example

import java.io.*;

class UnaryOperator{
	public static void main(String[] args)
	{
		int num1 = 3;
                  int num2 = num1++;
		System.out.println("After Post-Increment = " + num2);
	}
}        

Explanation

The example has a statement int num2 = num1++; which is a post-increment operation. It assigns the current value of num1 to num2 and then increments num1 by 1. 

Output

After Post-Increment = 3

4. Decrement Operator (--)

Similar to the increment operator, the decrement operator decreases the value of a variable by 1. It has two forms:

  • Pre-decrement Operator:

Syntax


--variable;

Example

import java.io.*;

class UnaryOperator{
	public static void main(String[] args)
	{
		int num1 = 3;
                  int num2 = --num1;
		System.out.println("After Pre-Decrement = " + num2);
	}
}

Explanation

In this code, the pre-decrement operator (--num1) is applied, which decrements the value of num1 by 1 before the assignment. The result is stored in the variable num2. Finally, the code prints the value of num2 using the System.out.println statement, displaying "After Pre-Decrement = 2" in the console.

Output

After Pre-Decrement = 2
  • Post-decrement Operator:

Syntax


variable--;

Example

import java.io.*;

class UnaryOperator{
	public static void main(String[] args)
	{
		int num1 = 3;
                  int num2 = num1--;
		System.out.println("After Post-Decrement = " + num2);
	}
}       

Explanation

The post-decrement operator (num1--) is then applied to num1, which means the current value of num1 is assigned to another variable (num2), and afterward, num1 is decremented by 1. Finally, the program execution in the Java Online Compiler prints the result of the post-decrement operation, showing the value of num2 after the decrement.

Output

After Post-Decrement = 3

5. Logical Complement Operator (!)

The logical complement operator is used to invert the value of a Boolean expression. If the operand is true, the result is false, and vice versa.

Syntax


!(variable);

Example

import java.io.*;

class UnaryOperator{
	public static void main(String[] args)
	{
		boolean num1 = true;
                  boolean num2 = !num1;
		System.out.println("After logical operator = " + num2);
	}
}

Explanation

The logical complement operator inverts the boolean value, so if num1 is true, num2 will be false, and vice versa. The output on execution by the Java Compiler will be: "After logical operator = false."

Output

After logical operator = false

Read More - Java Web Developer Salary

Example of Unary Operators in Java

public class UnaryOperatorsExample {
    public static void main(String[] args) {
        // Unary Plus and Minus
        int originalNumber = 8;
        int positiveValue = +originalNumber;
        int negativeValue = -originalNumber;

        System.out.println("Original Number: " + originalNumber);
        System.out.println("Unary Plus: " + positiveValue);
        System.out.println("Unary Minus: " + negativeValue);

        // Increment and Decrement
        int counter = 5;
        counter++; // Increment by 1
        System.out.println("After Increment: " + counter);

        counter--; // Decrement by 1
        System.out.println("After Decrement: " + counter);

        // Logical Complement
        boolean isJavaFun = true;
        boolean isJavaNotFun = !isJavaFun;
        System.out.println("Is Java fun? " + isJavaFun);
        System.out.println("Is Java not fun? " + isJavaNotFun);
    }
}     

Explanation

The code in our Java Online Editor essentially showcases the application of various unary operators in Java, offering a hands-on demonstration of their functionality. 

Output

Original Number: 8
Unary Plus: 8
Unary Minus: -8
After Increment: 6
After Decrement: 5
Is Java fun? true
Is Java not fun? false      

Advantages of Unary Operator in Java

  • Concise and Simple to Use: Unary operators just require one operand to function. They are simple to understand, making code more readable and concise.
  • Quicker than Other Operators: Compared to other operators, ternary operators are faster since they just need a single operand. This makes them excellent for actions that must be completed fast, such as increasing a counter.
  • Pre- and Post-Increment/Decrement: As unary operators support both pre- and post-increment and decrement, they are helpful in a wide range of applications. The pre-increment operator increases the value of a variable before it is used in an expression, whereas the post-increment operator increases the value of a variable after it has been used in an expression.
  • Updating Primitive Types: Unary operators can change the value of primitive types such as int, long, float, double, etc.
Read More
Summary
This was all about types of Java unary operators. A unary operator in Java is essential for manipulating individual operands efficiently. Whether it's changing signs, incrementing/decrementing values, or inverting Boolean expressions, unary operators provide powerful tools for developers. If you're interested in more tips and guidance, you may also consider our Java tutorial, which can validate your skills and enhance your credibility in the field.

FAQs

Yes, unary operators can be applied to various data types, including numeric types, Boolean, and objects.

The pre-increment operator (++variable) increments the variable's value before its value is used, while the post-increment operator (variable++) uses the current value of the variable before incrementing it.

The logical complement operator (!) inverts the value of a Boolean expression. If the operand is true, the result is false, and vice versa.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this