0
0
Javaprogramming~5 mins

Unary operators in Java

Choose your learning style9 modes available
Introduction

Unary operators help you change or check a single value quickly. They make your code shorter and easier to read.

When you want to increase or decrease a number by one, like counting steps.
When you want to flip a true/false value, like turning a light on or off.
When you want to get the positive or negative sign of a number.
When you want to check if a value is true or false in conditions.
When you want to simplify expressions by using shorthand operators.
Syntax
Java
++variable;  // increase by 1
--variable;  // decrease by 1
+variable;   // positive sign (usually no change)
-variable;   // negative sign (negates the value)
!boolean;    // logical NOT (flips true/false)

++ and -- can be used before (prefix) or after (postfix) a variable.

Logical NOT (!) only works with boolean values.

Examples
Prefix ++ increases a by 1 before using it.
Java
int a = 5;
++a;  // a becomes 6
Postfix -- decreases b by 1 after using it.
Java
int b = 5;
b--;  // b becomes 4
Logical NOT flips false to true.
Java
boolean lightOn = false;
lightOn = !lightOn;  // lightOn becomes true
Unary minus changes sign of c.
Java
int c = -10;
int d = -c;  // d becomes 10
Sample Program

This program shows how unary operators ++, --, !, and unary minus work. It prints values before and after applying these operators.

Java
public class UnaryOperatorsDemo {
    public static void main(String[] args) {
        int count = 10;
        System.out.println("Original count: " + count);

        System.out.println("Using prefix ++: " + (++count));
        System.out.println("After prefix ++, count: " + count);

        System.out.println("Using postfix --: " + (count--));
        System.out.println("After postfix --, count: " + count);

        boolean isActive = false;
        System.out.println("Original isActive: " + isActive);
        System.out.println("After !isActive: " + !isActive);

        int number = -5;
        System.out.println("Original number: " + number);
        System.out.println("Unary minus applied: " + (-number));
    }
}
OutputSuccess
Important Notes

Prefix ++/-- changes the value before using it in an expression.

Postfix ++/-- changes the value after using it in an expression.

Unary plus (+) usually does not change the value but can be used for clarity.

Summary

Unary operators work on one value to change or check it.

Use ++ and -- to add or subtract one quickly.

Use ! to flip true/false values.