Unary Operators in Java

  • Last Updated: September 13, 2023
  • By: javahandson
  • Series
img

Unary Operators in Java

Unary operators in Java are operators that work on just one value. They add one, take one away, flip a sign, or invert a true into a false. This guide walks through each one in plain English with runnable examples.

1. Introduction

Most operators in Java need two values to do their job. Addition needs two numbers. A comparison needs a left side and a right side. But some operators are happy with just one value.

These one-value operators are the unary operators. The word “unary” simply means “one”. They act on a single operand and hand back a result.

You use them all the time, often without noticing. Every counting loop leans on one. Every “if not ready” check leans on another. They are small, but they show up on nearly every page of Java code.

1.1 What This Article Covers

We build up from the basics, one operator at a time. Here is the plan:

  • What a unary operator is, and why it needs only one operand
  • The five unary operators and what each one does
  • Unary plus and unary minus, with a runnable example
  • The increment and decrement operators, in their pre and post forms
  • The logical NOT operator that flips a boolean
  • Common mistakes, a real walkthrough, and interview questions

You need no special setup to follow along. A basic grasp of variables is enough, and every example is short enough to paste and run.

2. What Is a Unary Operator?

A unary operator acts on exactly one operand. That operand can be a variable or a plain literal value. The operator reads it, does its job, and produces a result.

Compare this with a binary operator like plus. Addition needs two numbers, one on each side. A unary operator sits happily next to a single value instead.

2.1 One Operand Is All It Needs

Think about the minus sign in -5. There is only one number here, the 5. The minus flips its sign, so you get negative five.

That is a unary operator at work. It took one value and gave back a result. Most unary operators work on numbers, while one of them, the NOT operator, works on a boolean.

2.2 The Five Unary Operators

Java gives you five everyday unary operators. This table lists them with their jobs:

Operator Name What It Does
+ Unary plus Keeps the value as it is, like multiplying by +1
Unary minus Flips the sign, like multiplying by -1
++ Increment Adds 1 to the value
Decrement Takes 1 away from the value
! Logical NOT Flips a boolean, so true becomes false

The first four work on numbers. The last one works on a boolean. We will meet each in its own section.

3. Unary Plus and Unary Minus

Let us start with the two sign operators. Unary plus leaves a value alone, while unary minus flips its sign. They look alike but behave very differently.

Why keep an operator that does nothing? Unary plus is like multiplying by +1. People mostly use it to show intent, not to change a value. Unary minus is the useful one, since it turns a positive number negative and a negative number positive.

3.1 A Runnable Example

Here we take one positive value and one negative value. We apply both sign operators to each and print the results:

package com.java.handson.operators;

public class UnaryOperators {
    public static void main(String[] args) {

        int result = 10; // a positive value

        int unaryPlusResult = +result;
        System.out.println("Unary plus on 10 : " + unaryPlusResult);

        int unaryMinusResult = -result;
        System.out.println("Unary minus on 10 : " + unaryMinusResult);

        int output = -20; // a negative value

        int unaryPlusOutput = +output;
        System.out.println("Unary plus on -20 : " + unaryPlusOutput);

        int unaryMinusOutput = -output;
        System.out.println("Unary minus on -20 : " + unaryMinusOutput);
    }
}

// Output:
// Unary plus on 10 : 10
// Unary minus on 10 : -10
// Unary plus on -20 : -20
// Unary minus on -20 : 20

3.2 Reading the Output

Look at the first two lines. Unary plus left 10 as 10, while unary minus turned 10 into negative ten.

Now look at the last two lines. Unary plus left negative twenty untouched. Unary minus flipped it back to positive twenty. So the pattern is clear: plus never changes the value, and minus flips the sign every time.

3.3 A Common Use of Unary Minus

You reach for unary minus whenever you need the opposite of a value. Say a bank stores a withdrawal as a negative change. You can build that from a positive amount:

int amount = 500;

int withdrawal = -amount;
System.out.println("Change to balance : " + withdrawal); // Output: Change to balance : -500

The amount here is a plain positive number, and unary minus flips it to negative five hundred. Any time a value needs to point the other way, this operator does the job in one keystroke.

4. The Increment Operator

The increment operator adds one to a value. We write it as two plus signs, ++. It saves you from typing x = x + 1 by hand.

This operator comes in two flavours. One is post-increment, and the other is pre-increment. They both add one, but they differ in timing.

4.1 Post-Increment

Post-increment writes the plus signs after the variable, like a++. It uses the current value first, then adds one. In short, it acts, then it updates.

int result = 10;

System.out.println("Value of result is : " + result++);
System.out.println("Value of result is : " + result);

// Output:
// Value of result is : 10
// Value of result is : 11

The first print runs before the update, so it shows 10, the old value. Right after, Java adds one, so the second print shows 11. This “use then change” order is the mark of the post form.

4.2 Pre-Increment

Pre-increment writes the plus signs before the variable, like ++a. It adds one first, then uses the new value. In short, it updates, then it acts.

int output = 20;

System.out.println("Value of output is : " + ++output);
System.out.println("Value of output is : " + output);

// Output:
// Value of output is : 21
// Value of output is : 21

Here Java adds one before the first print, so that print already shows 21. The value stays at 21, so the second print shows 21 as well. This “change then use” order is the mark of the pre form.

4.3 Both in One Program

Let us put both forms side by side. This makes the timing difference easy to see:

int result = 10;
System.out.println("Post-increment shows : " + result++);
System.out.println("Now result is        : " + result);

int output = 20;
System.out.println("Pre-increment shows : " + ++output);
System.out.println("Now output is        : " + output);

// Output:
// Post-increment shows : 10
// Now result is        : 11
// Pre-increment shows : 21
// Now output is        : 21

The post form printed the old value, then moved on. The pre form printed the new value straight away. Both variables ended one higher than they started.

5. The Decrement Operator

The decrement operator takes one away from a value. We write it as two minus signs, --. It is the mirror image of increment.

Like increment, it has two forms. Post-decrement acts before it updates. Pre-decrement updates before it acts.

5.1 Post-Decrement

Post-decrement puts the minus signs after the variable, like a--. It uses the current value first, then subtracts one.

int result = 10;

System.out.println("Value of result is : " + result--);
System.out.println("Value of result is : " + result);

// Output:
// Value of result is : 10
// Value of result is : 9

The first print shows 10, the value before the change. Java then subtracts one, so the second print shows 9. It mirrors post-increment, only it counts down instead of up.

5.2 Pre-Decrement

Pre-decrement puts the minus signs before the variable, like --a. It subtracts one first, then uses the new value.

int output = 20;

System.out.println("Value of output is : " + --output);
System.out.println("Value of output is : " + output);

// Output:
// Value of output is : 19
// Value of output is : 19

Java subtracts one before the first print, so that print already shows 19. The value holds at 19, so the second print matches, just as pre-increment behaved earlier.

6. Pre vs Post at a Glance

The pre and post forms confuse many beginners. A quick summary clears it up. The change is always the same, only the timing shifts.

6.1 The Difference in One Table

This table sums up the two forms for both operators:

Form Example Order of Work
Post-increment a++ Use the value, then add 1
Pre-increment ++a Add 1, then use the value
Post-decrement a– Use the value, then subtract 1
Pre-decrement –a Subtract 1, then use the value

On its own line, pre and post give the same result. Both a++; and ++a; just add one. The gap only shows when you use the value in the same statement.

6.2 A Timing Example That Bites

Let us see the timing gap in real code. We assign one value using each form and watch the results split:

int a = 5;
int postValue = a++;   // postValue gets 5, then a becomes 6
System.out.println("postValue : " + postValue + ", a : " + a);

int b = 5;
int preValue = ++b;    // b becomes 6, then preValue gets 6
System.out.println("preValue  : " + preValue + ", b : " + b);

// Output:
// postValue : 5, a : 6
// preValue  : 6, b : 6

Both variables ended at six, but the stored values differ. Post-increment gave postValue the old five, while pre-increment gave preValue the new six. That tiny gap is a common source of off-by-one bugs.

7. The Logical NOT Operator

The last unary operator is logical NOT. We write it as an exclamation mark, !. It works on a boolean, not a number.

Its job is simple. It flips a boolean to its opposite. A true becomes false, and a false becomes true.

7.1 Flipping a Boolean

Here we start with a false flag. The NOT operator flips it, so the if block runs:

package com.java.handson.operators;

public class NotDemo {
    public static void main(String[] args) {

        boolean isValid = false;

        if (!isValid) {
            System.out.println("isValid was false, so NOT made it true");
        }
    }
}

// Output:
// isValid was false, so NOT made it true

Our flag isValid starts as false. NOT then flips it to true for the check, so the if condition passes and the message prints. You often want to run a block when something is not ready, and NOT says exactly that in one character.

7.2 Unary Operators in a Loop

Unary operators shine inside loops. The classic for loop uses increment to move forward:

for (int i = 1; i <= 5; i++) {
    System.out.println("Count is : " + i);
}

// Output:
// Count is : 1
// Count is : 2
// Count is : 3
// Count is : 4
// Count is : 5

The i++ part runs at the end of each pass and nudges the counter up by one. Without it, the loop would spin forever. Nearly every for loop you write uses increment right here.

Decrement drives a countdown just as neatly. Here a while loop ticks from three down to one:

int count = 3;

while (count > 0) {
    System.out.println("Countdown : " + count);
    count--;
}
System.out.println("Liftoff!");

// Output:
// Countdown : 3
// Countdown : 2
// Countdown : 1
// Liftoff!

Each pass prints the count and then drops it by one. Once the count hits zero, the loop stops and the final message prints just once.

8. Common Mistakes and Pitfalls

Unary operators are simple, yet a few traps catch beginners. Watch for these three.

8.1 Confusing Pre and Post

The most common slip mixes up pre and post. People expect x++ to use the new value right away. Inside a print or an assignment, it does not.

Slow down when the operator sits inside a bigger line. Ask yourself which value you actually need, then pick pre or post to match.

8.2 Changing a Variable Twice

Do not change one variable twice in a single statement. A line like x = x++ + ++x; is a puzzle, not code. It confuses both readers and your future self.

Keep each statement simple. Change a variable once per line, since clear code always beats a clever one-liner.

8.3 Using NOT on a Non-Boolean

The NOT operator works only on a boolean. You cannot apply it to a number in Java. A line like !5 will not compile.

Some languages let you flip a number this way, but Java does not. Give the NOT operator a real boolean, and it behaves.

9. A Practical Walkthrough

Let us tie the ideas together in one small program. We will track a stock of items as they sell and restock.

9.1 A Small Counter Program

This program uses increment, decrement, and NOT together:

package com.java.handson.operators;

public class StockTracker {
    public static void main(String[] args) {

        int stock = 3;
        boolean open = true;

        stock++;                 // a delivery adds one item
        System.out.println("After delivery : " + stock);

        stock--;                 // a sale removes one item
        System.out.println("After a sale   : " + stock);

        open = !open;            // the shop closes for the day
        System.out.println("Shop open?     : " + open);
    }
}

// Output:
// After delivery : 4
// After a sale   : 3
// Shop open?     : false

9.2 Reading the Result

The stock starts at three. A delivery uses increment, so it climbs to four. A sale uses decrement, so it drops back to three.

The last step flips the open flag with NOT. The shop was open, so now it reads false. Three tiny operators drive the whole story, and each one changes a single value in a single, clear step.

10. Interview Questions

Q: What is a unary operator in Java?

A: It is an operator that works on a single operand. Java has five common ones: unary plus, unary minus, increment, decrement, and logical NOT. Each takes one value and returns a result.

Q: What is the difference between pre-increment and post-increment?

A: Pre-increment adds one first and then uses the new value. Post-increment uses the current value first and then adds one. On a line by itself both give the same result, but inside a larger expression the timing changes the answer.

Q: Does the unary plus operator change a value?

A: No, unary plus leaves the value exactly as it was. It is like multiplying by positive one. People mostly use it to show intent rather than to change anything.

Q: What does the logical NOT operator do?

A: It flips a boolean to its opposite. A true becomes false, and a false becomes true. It works only on a boolean, so you cannot apply it to a number.

Q: Can I use increment and decrement on other types?

A: Yes, they work on all the number types, such as int, long, double, and even char. On a char, increment moves to the next character in order. The idea stays the same: add or take away one.

11. Conclusion

Let us wrap up what we covered. Unary operators in Java work on a single operand. The five everyday ones are unary plus, unary minus, increment, decrement, and logical NOT.

We saw how unary minus flips a sign, how increment and decrement shift a value by one, and how NOT flips a boolean. We also compared the pre and post forms, which differ only in timing.

These operators are small, but they are everywhere. Keep the pre and post rule firmly in mind, and you will sidestep the classic off-by-one bug.

Further Reading

Leave a Comment