Java Unary Operators Explained: ++, --, +, -, ! and ~ with Examples

0

Sometimes a program needs to work with just one value instead of comparing or combining two values. You may need to increase a counter, decrease a number, reverse a boolean condition, or change the sign of a numeric value. Java provides unary operators specifically for these situations.

A unary operator works with a single operand. Although these operators are small, they appear constantly in Java code, especially inside loops, counters, conditional expressions, and calculations.

Why Unary Operators Matter

Consider a program that processes customer records one by one. Every time a record is processed, a counter needs to increase by one. Writing count++ expresses that operation directly and clearly.

Unary operators make simple transformations concise while keeping the intention of the code easy to recognize.

Important: A unary operator operates on exactly one operand. The operand may be a variable, constant, or expression depending on the operator.

Unary Operators at a Glance

Operator Name Purpose Example
+ Unary plus Indicates a positive numeric value +number
- Unary minus Negates a numeric value -number
++ Increment Increases a value by one count++
-- Decrement Decreases a value by one count--
! Logical NOT Reverses a boolean value !active
~ Bitwise complement Flips every bit of an integer value ~number

Unary Plus (+)

The unary plus operator indicates that a numeric value is positive. In most everyday Java code, it does not change the value.

int number = 10;

int result = +number;

System.out.println(result);

The result is 10. Unary plus is rarely necessary because positive numeric values are normally written without it.

Unary Minus (-)

The unary minus operator changes the sign of a numeric value.

int number = 10;

int result = -number;

System.out.println(result);

The result is -10. If the original value is negative, applying unary minus produces a positive value.

int number = -25;

int result = -number;

System.out.println(result);

The result is 25.

Increment Operator (++)

The increment operator increases a numeric variable by one.

int count = 5;

count++;

System.out.println(count);

After the increment, count becomes 6.

Conceptually, count++ performs the same value update as count = count + 1, but the increment operator becomes particularly useful inside loops and compact expressions.

Decrement Operator (--)

The decrement operator decreases a numeric variable by one.

int lives = 3;

lives--;

System.out.println(lives);

The value becomes 2.

Decrement is useful for countdowns, reverse iteration, resource tracking, and many other situations where a value needs to decrease one step at a time.

Prefix and Postfix Increment

The increment operator has two forms: prefix and postfix. The difference becomes important when the increment operation is part of a larger expression.

Postfix Increment

With postfix increment, the current value is used first, and the variable is incremented afterward.

int number = 10;

int result = number++;

System.out.println(result);
System.out.println(number);

The value assigned to result is 10. After that, number becomes 11.

Prefix Increment

With prefix increment, the variable is incremented first, and the new value is then used in the expression.

int number = 10;

int result = ++number;

System.out.println(result);
System.out.println(number);

The variable first becomes 11, and that new value is assigned to result.

Form Order Example Value Used by Expression
Postfix Use, then increment x++ Old value
Prefix Increment, then use ++x New value

Remember: The variable changes in both forms. The difference is when the old or new value is used by the surrounding expression.

Prefix and Postfix Decrement

The same distinction applies to the decrement operator.

int number = 10;

int first = number--;
int second = --number;

System.out.println(first);
System.out.println(second);
System.out.println(number);

The postfix form uses the old value before decreasing the variable. The prefix form decreases the variable first and then uses the new value.

Logical NOT Operator (!)

The logical NOT operator reverses a boolean value. It is also a unary operator because it operates on one operand.

boolean active = true;

boolean inactive = !active;

System.out.println(inactive);

Because active is true, !active becomes false.

The NOT operator is especially useful when expressing the opposite of an existing condition.

boolean loggedIn = false;

if (!loggedIn) {
    System.out.println("Please log in.");
}

The condition reads naturally: if the user is not logged in, display the message.

Bitwise Complement Operator (~)

The bitwise complement operator ~ flips every bit in an integer value. A binary zero becomes one, and a binary one becomes zero.

int number = 5;

int result = ~number;

System.out.println(result);

The result is -6 because Java uses two's complement representation for signed integer values. The identity ~x = -(x + 1) is a useful shortcut for understanding the result of bitwise complement on signed integers.

The ~ operator is more common in low-level programming, bit manipulation, flags, and performance-sensitive code than in everyday application logic.

Unary Operators and Expressions

Unary operators can be combined with other operators, but precedence matters.

int number = 5;

int result = -number * 2;

System.out.println(result);

The unary minus applies to number, producing -5. That value is then multiplied by 2, producing -10.

Parentheses can make the intended calculation explicit when an expression becomes more complicated.

Increment and Decrement in Loops

One of the most common places to see ++ and -- is a for loop.

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

After each iteration, i++ increases the counter by one. This produces the sequence 0, 1, 2, 3, 4.

The decrement operator is useful when iterating in the opposite direction.

for (int i = 5; i > 0; i--) {
    System.out.println(i);
}

Here, the counter decreases after each iteration, producing a countdown.

A Common Trap with Multiple Increments

Although Java allows multiple increment or decrement operations in one expression, writing code that changes the same variable several times within a single statement can make the result difficult to understand.

int x = 5;

int result = x++ + ++x;

System.out.println(result);
System.out.println(x);

Java evaluates the expression according to its language rules, but code like this is unnecessarily difficult to read and maintain. In professional code, separate statements are usually clearer when multiple changes to the same variable are involved.

Professional tip: Just because Java allows a compact expression does not mean the expression is good code. Prefer clarity when incrementing or decrementing a variable multiple times.

Common Beginner Mistakes

  • Confusing prefix ++x with postfix x++.
  • Forgetting that postfix uses the old value in the surrounding expression.
  • Assuming ! can be used with numeric values. It operates on boolean expressions.
  • Using ~ without understanding signed integer representation.
  • Changing the same variable several times in one expression and making the code difficult to reason about.
  • Using increment or decrement on an expression that is not a modifiable variable.

Practical Example: Processing Items

Suppose a program processes ten items. A counter can be updated naturally using the increment operator.

int processed = 0;

processed++;
processed++;
processed++;

System.out.println("Processed: " + processed);

Each processed++ operation increases the counter by one. The final value is 3.

In a real application, the same idea would usually appear inside a loop or processing method.

Best Practices

  • Use ++ and -- naturally for counters and iteration.
  • Use prefix and postfix forms intentionally when their expression values matter.
  • Prefer separate statements when multiple modifications to the same variable would make an expression difficult to understand.
  • Use ! to express clear boolean negation.
  • Use ~ only when bitwise manipulation is actually required.
  • Do not sacrifice readability simply to make an expression shorter.

Interview Insights

A classic interview question asks for the difference between x++ and ++x. The best explanation is concise: postfix increment returns the current value and then increments the variable, while prefix increment increments the variable first and then returns the new value.

Interviewers may also ask whether i++ and i += 1 both increase a variable by one. As a standalone update, they both increase the value by one, but they behave differently when their resulting value participates in a larger expression.

Quick Revision

Operator Purpose Example Key Point
+ Unary plus +x Indicates positive value
- Unary minus -x Reverses numeric sign
++ Increment x++ Increases by one
-- Decrement x-- Decreases by one
! Logical NOT !active Reverses boolean value
~ Bitwise complement ~x Flips integer bits

Final Takeaway

Unary operators may work on only one operand, but they perform some of the most frequently used operations in Java. The most important ones to master are ++, --, and !, especially the difference between prefix and postfix forms. Use these operators confidently, but remember that readable code is more valuable than clever code. When an expression becomes difficult to understand, break it into simple steps.

Post a Comment

0Comments
Post a Comment (0)