Unary Operator | Java

Unary Operator | Java

Basics • Java Fundamentals

Unary operators in Java are operators that operate on a single operand. They are used to perform various operations such as incrementing/decrementing a value, negating a value, or inverting the bits of a value. Here are the main unary operators in Java:

  1. Unary Plus (+):

    • Indicates a positive value. While it doesn't change the sign of positive numbers, it can be used to emphasize the positive sign.
    int x = 5;
    int result = +x; // result is 5
  1. Unary Minus (-):

    • Negates the value of its operand.
    int y = 8;
    int result = -y; // result is -8
  1. Increment (++):
  • Increases the value of its operand by 1.

  •   int a = 3;
      a++; // a is now 4
    

There are two types of implement operators -

  • Post Increment: First initialise then increase.

  • Pre Increment: First increase then initialise.

For example -

ExpressionInitial value of xValue of yFinal value
y = x++101011
y = ++x101111
  1. Decrement (--):
  • Decreases the value of its operand by 1.

  •   int b = 7;
      b--; // b is now 6
    

There are two types of implement operators -

  • Post Increment: First initialise then increase.

  • Pre Increment: First increase then initialise.

For example -

ExpressionInitial value of xInitial value of yFinal value
y = x--10109
y = --x1099

It's important to note that the increment and decrement operators can be used as a prefix (++a or --a) or a postfix (a++ or a--). The difference between the two lies in when the increment or decrement is applied in relation to the surrounding expression.

  1. Logical Complement (!):
  • Inverts the logical state of its operand. If the operand is true, the result is false, and if the operand is false, the result is true.

  • This operator is only applicable for boolean.

  •   boolean flag = true;
      boolean result = !flag; // result is false
    
  • Bitwise Complement (~):

    • Inverts the bits of its operand, changing 1s to 0s and vice versa.

    • This operator is only applicable for integral not for boolean.

  •   int number = 5; // binary: 0000 0000 0000 0000 0000 0000 0000 0101
      int result = ~number; // binary: 1111 1111 1111 1111 1111 1111 1111 1010 (-6 in decimal)
    

Unary operators are essential in various programming scenarios, and they play a crucial role in expressions and statements. Understanding how these operators work is fundamental for writing efficient and correct Java code.

Did you find this article valuable?

Support Xander | ᓕᘏᗢ by becoming a sponsor. Any amount is appreciated!