Java Unary Operators
Table of Contents + β
In the last lesson you learned about Java logical operators. Some jobs have only one value to work on: counting up by one, flipping true into false, making a number negative. Java has a family of operators for exactly this, called unary operators.
π€ Why one-operand operators?
Counting visitors? You could write count = count + 1 every time. But that is long, and you type the name twice:
- A unary operator works on a single value, not two.
count++does the same job ascount = count + 1, just shorter.- You already met one: the
!that flips a boolean.
Here is the whole family this lesson covers.
+unary plus, keeps a number as it is.-unary minus, makes a number negative.++increment, adds one.--decrement, takes one away.!logical NOT, flips a boolean.~bitwise complement, flips the bits (a quick look only).
β Unary plus and minus
The two easiest ones:
+in front of a number does nothing useful. It just says βthis number, as it isβ.-flips the sign. Positive becomes negative, negative becomes positive.
The code below shows both signs on a few numbers.
int profit = 50;int loss = -30;
System.out.println(+profit);System.out.println(-profit);System.out.println(-loss);Line by line:
+profitis just50. The plus changed nothing.-profitflips50into-50.-lossflips-30into30, becauselosswas already negative.
Output
50-5030The unary minus is the one you will actually reach for. Unary plus is rarely used, because a plain number is already positive.
ββ Increment with ++
The increment operator ++ adds one to a variable. x++ is the same as x = x + 1, just shorter.
The code below increments a score a couple of times.
int score = 10;score++;System.out.println(score);
score++;System.out.println(score);Walk through it:
scorestarts at10.- The first
score++bumps it to11. - The second
score++bumps it to12.
Output
1112The variable climbs by one each time. The decrement operator is the mirror image.
ββ Decrement with β
The decrement operator -- is the opposite of ++. It takes one away. So x-- means x = x - 1. Perfect for counting down lives in a game.
The code below removes a life twice.
int lives = 3;lives--;System.out.println(lives);
lives--;System.out.println(lives);Read it through:
livesstarts at3.- The first
lives--drops it to2. - The second
lives--drops it to1.
Output
21On their own line, ++ and -- are easy. But a twist shows up when you use them inside a bigger expression.
π Prefix vs postfix: the big one
You can write ++ in two places, and both add one to x. The variable ends up the same. What changes is the value the expression hands back.
- Prefix
++x:++comes before. It adds one first, then gives back the new value. - Postfix
x++:++comes after. It gives back the old value first, then adds one.
The code below uses postfix. Watch what gets stored in b.
int a = 5;int b = a++;System.out.println("a = " + a);System.out.println("b = " + b);The heart of the lesson:
astarts at5.int b = a++is postfix, so Java hands back the old5and stores it inb.- Then
agets its plus one, becoming6. - Result:
bis5, butais6.
Output
a = 6b = 5Now the same code with prefix. One character moves, and b changes.
int a = 5;int b = ++a;System.out.println("a = " + a);System.out.println("b = " + b);Step through the difference:
astarts at5.int b = ++ais prefix, so Java adds one first, makingabecome6.- That new
6is handed back and stored inb. - Result:
bis6, andais6as well.
Output
a = 6b = 6See the pattern? In both cases a ended at 6. Only b changed:
- Postfix gave
bthe old5: it uses the value, then changes it. - Prefix gave
bthe new6: it changes the value, then uses it.
Tip
A memory trick. Read the symbols left to right. In a++, the a comes first, so the value of a is used first. In ++a, the ++ comes first, so the adding happens first.
π Increment and decrement in loops
The most common home for ++ is a loop. A for loop counts through a range, and ++ moves the count forward each round. The code below prints one to five.
for (int i = 1; i <= 5; i++) { System.out.println(i);}Each time around:
istarts at1.- After the body runs,
i++adds one toi. - The loop keeps going while
i <= 5is true.
Output
12345Does i++ or ++i matter here? For a normal for loop, no:
- Nothing stores the result, so the returned value is thrown away.
- The loop only cares that
igoes up by one, and both forms do that. for (int i = 1; i <= 5; ++i)prints the same thing.- Prefix-versus-postfix only matters when you use the returned value, like
int b = a++earlier.
A countdown loop is just as common. Here -- walks a number down to one.
for (int count = 3; count >= 1; count--) { System.out.println(count + "...");}System.out.println("Go!");count starts at 3, drops by one each round until it reaches one, then prints the final message.
Output
3...2...1...Go!β The logical NOT (!)
You met ! in the logical operators lesson, but it belongs here too because it is unary.
- The logical NOT takes one boolean and flips it.
truebecomesfalse, andfalsebecomestrue.- It works only on booleans, not numbers.
The code below flips a couple of boolean values.
boolean isOnline = true;System.out.println(!isOnline);
boolean isEmpty = false;System.out.println(!isEmpty);Read it through:
isOnlineistrue, so!isOnlineflips it tofalse.isEmptyisfalse, so!isEmptyflips it totrue.
Output
falsetrueYou will use ! a lot inside if statements when you care about the opposite of a check. if (!isLoggedIn) reads as βif the user is not logged inβ.
π§ The bitwise complement (~)
The last unary operator is ~, the bitwise complement:
- It works on the individual bits of a whole number.
- It flips every bit: each
0becomes1, each1becomes0. - For everyday integers, the short rule is
~nequals-n - 1.
The code below shows that rule on a small number.
int n = 5;System.out.println(~n);Here n is 5, so ~n works out to -5 - 1, which is -6.
Output
-6Do not worry if this feels strange. You will rarely touch ~ in normal app code. The full story of bits lives in the next lesson.
β οΈ Common Mistakes
The ++ and -- operators cause more confusion than any other beginner topic. Watch for these slip-ups.
Mixing up prefix and postfix when the value is used. Storing the result, the position changes what gets stored.
// β Avoid: expecting b to be 6 here. Postfix gives the OLD value, so b is 5// int a = 5;// int b = a++; // b becomes 5, not 6
// β
Good: use prefix when you want the NEW valueint a = 5;int b = ++a; // b becomes 6System.out.println(b);Using ++ inside a complex expression. Mixing ++ into a long line makes the result hard to predict and hard to read. Pull it onto its own line.
// β Avoid: this is confusing and easy to get wrong// int x = 5;// int result = x++ + ++x;
// β
Good: change x clearly, then use itint x = 5;x++;int result = x + x;System.out.println(result);Changing the same variable twice in one statement. Writing something like i = i++ + 1 looks clever but the result surprises almost everyone. Keep one change per statement.
// β Avoid: two changes to i in one line is a classic trap// int i = 5;// i = i++; // i stays 5, which is almost never what you wanted
// β
Good: one clear actionint i = 5;i++; // i becomes 6System.out.println(i);Trying to increment a literal number. ++ needs a variable to store the new value back into. 5++ makes no sense, and Java will refuse to compile it.
// β Avoid: you cannot increment a plain number// System.out.println(5++);
// β
Good: increment a variableint value = 5;value++;System.out.println(value);β Best Practices
A few habits keep increment and decrement code clean and safe.
- Keep
++and--on their own line when you can.count++;on its own is crystal clear. Buried inside a big expression, it is a guessing game. - Prefer postfix
i++in plainforloops. It is the common style, and the returned value is ignored there anyway, so it reads naturally. - Reach for prefix
++xonly when you really want the new value. And when you do, add a short comment so the next reader knows it was on purpose. - Never change the same variable twice in one statement. One change per line keeps the result obvious.
- Name booleans for the positive case. Then
!isReadyreads cleanly, instead of a confusing double negative like!isNotReady.
π§© What Youβve Learned
Nice work. The prefix-versus-postfix idea trips up a lot of people, and you just worked through it.
- β A unary operator works on a single value, not two.
- β
Unary
-flips the sign of a number; unary+leaves it unchanged. - β
++adds one and--takes one away. - β
Postfix
x++gives the old value first, then adds one. - β
Prefix
++xadds one first, then gives the new value. - β
In a normal
forloop,i++and++ibehave the same, because the result is not used. - β
!flips a boolean, and~flips the bits of a number.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does b hold after int a = 5; int b = a++;?
Why: Postfix a++ hands back the OLD value of a, which is 5, so b is 5. After that, a becomes 6.
- 2
What does b hold after int a = 5; int b = ++a;?
Why: Prefix ++a adds one to a first, making it 6, and then returns that new value, so b is 6.
- 3
In a plain for loop like for (int i = 0; i < 5; i++), does using ++i instead change the result?
Why: The loop only needs i to go up by one. The returned value is ignored, so i++ and ++i behave the same here.
- 4
What does the ! operator do?
Why: The logical NOT (!) works on a single boolean and reverses it: true becomes false and false becomes true.
π Whatβs Next?
You met the bitwise complement ~ briefly in this lesson. There is a whole set of operators that work on the individual bits of a number, and they unlock some clever, fast tricks. Letβs dig into them next.