๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Unary Operators in Java  


Introduction

  • Unary operators in Java are used to perform operations on a single operand.
  • Unary operators are used to simplify expressions and perform operations like incrementing or negating a value with minimal syntax.
  • For example :-
    • Negating a value: Achieved using the unary minus (-) or logical NOT (!).
    • Incrementing/Decrementing: Done using ++ (increment) or -- (decrement).
    • Logical Negation: Achieved using !, which inverts a boolean value.
    • etc...
  • Unary operators are explained as below :-
    • + (Unary plus operator):
      • Purpose: Represents a positive value. Often used to emphasize that a value is positive, though it is not commonly used because values are positive by default.
      • Example:
        int a = +5;
        System.out.println(a); // Output: 5
    • - (Unary Minus Operator):
      • Purpose: Negates a value, changing its sign from positive to negative or vice versa.
      • Example:
        int a = 5;
        System.out.println(-a); // Output: -5
    • ++ (Increment Operator):
      • Purpose: Increases the value of a variable by 1. Can be used in two forms:
        • Pre-Increment (++a): Increments the value first, then uses it.
        • Post-Increment (a++): Uses the value first, then increments it.
      • Example:
        int a = 5;
        System.out.println(++a); // Output: 6 (Pre-increment)
        System.out.println(a++); // Output: 6 (Post-increment)
        System.out.println(a);   // Output: 7
    • -- (Decrement Operator):
      • Purpose: Decreases the value of a variable by 1. Can also be used in two forms:
        • Pre-Decrement (--a): Decrements the value first, then uses it.
        • Post-Decrement (a--): Uses the value first, then decrements it.
      • Example:
        int a = 5;
        System.out.println(--a); // Output: 4 (Pre-decrement)
        System.out.println(a--); // Output: 4 (Post-decrement)
        System.out.println(a);   // Output: 3
    • ! (Logical NOT Operator):
      • Purpose: Inverts the value of a boolean expression. If the expression is true, it becomes false, and vice versa.
      • Example:
        boolean isTrue = true;
        System.out.println(!isTrue); // Output: false
  • Program:
    public class UnaryOperators
    {
        public static void main(String[] args)
        {
            // Initialize variables
            int a = 5, b = -10;
            boolean isTrue = true;
    
            // Unary Plus (+)
            System.out.println("Unary Plus (+a): " + (+a)); // Output: 5
    
            // Unary Minus (-)
            System.out.println("Unary Minus (-b): " + (-b)); // Output: 10
    
            // Pre-Increment (++a)
            System.out.println("Pre-Increment (++a): " + (++a)); // Output: 6
    
            // Post-Increment (a++)
            System.out.println("Post-Increment (a++): " + (a++)); // Output: 6
            System.out.println("Value after Post-Increment: " + a); // Output: 7
    
            // Pre-Decrement (--a)
            System.out.println("Pre-Decrement (--a): " + (--a)); // Output: 6
    
            // Post-Decrement (a--)
            System.out.println("Post-Decrement (a--): " + (a--)); // Output: 6
            System.out.println("Value after Post-Decrement: " + a); // Output: 5
    
            // Logical NOT (!)
            System.out.println("Logical NOT (!isTrue): " + (!isTrue)); // Output: false
    
            // Bitwise Complement (~)
            System.out.println("Bitwise Complement (~a): " + (~a)); // Output: -6
        }
    }
    Output:
    Unary Plus (+a): 5
    Unary Minus (-b): 10
    Pre-Increment (++a): 6
    Post-Increment (a++): 6
    Value after Post-Increment: 7
    Pre-Decrement (--a): 6
    Post-Decrement (a--): 6
    Value after Post-Decrement: 5
    Logical NOT (!isTrue): false
    Bitwise Complement (~a): -6
Some Advance Important Points :-
  • Unary Operators with Literals:
    • Unary operators can be directly applied to literals or variables.
    • Example: System.out.println(-5); outputs -5.
  • Unary Plus with Non-Numeric Types:
    • The unary plus (+) operator is valid only for numeric types.
    • Example: +true; will result in a compilation error because true is a boolean.
  • Increment/Decrement Operators in Expressions:
    • When used in complex expressions, the result depends on whether the operator is pre or post.
    • Example:
      int a = 5;
      int result = a++ + 10; // Post-increment: result = 15, a = 6
  • Increment/Decrement on Non-Variables:
    • Increment (++) and decrement (--) operators must be applied to variables, not constants or expressions.
    • Example: 5++; or (a + b)++; is invalid.
  • Logical NOT (!) with Non-Boolean Types:
    • The ! operator only works with boolean expressions.
    • Example: !5; results in a compilation error, but !true; is valid.
  • Unary Operators and Precedence:
    • Unary operators have higher precedence than binary operators but lower than parentheses.
    • Example:
      int a = 5, b = 10;
      System.out.println(-a + b); // Output: 5 (evaluates as (-a) + b)
  • Chained Increment/Decrement:
    • Multiple increments or decrements can be chained, but their evaluation follows left-to-right associativity.
    • Example:
      int a = 5;
      System.out.println(++a + ++a); // Output: 13 (evaluates as (++6) + (++7))
  • Unary Operators with Final Variables:
    • Increment and decrement operators cannot modify final variables.
    • Example:
      final int a = 5;
      a++; // Compilation error
  • Unary Operators with Char:
    • Increment and decrement can operate on char types, moving to the next or previous Unicode value.
    • Example:
      char c = 'A';
      System.out.println(++c); // Output: B
  • Efficiency in Loop Counters:
    • Pre-increment (++i) is slightly more efficient than post-increment (i++) in loops due to avoiding a temporary variable.
    • Example:
      for (int i = 0; i < 10; ++i)
      {
          System.out.println(i);
      }
  • Overflow/Underflow with Increment/Decrement:
    • Incrementing or decrementing numeric types can lead to overflow or underflow.
    • Example:
      int a = Integer.MAX_VALUE;
      System.out.println(++a); // Output: Integer.MIN_VALUE (overflow)
  • Unary Operators with Compound Expressions:
    • Unary operators can modify variables directly used in complex expressions.
    • Example:
      int a = 5;
      int b = (++a * 2) + (--a); // a becomes 6, then 5 again; result = 17
  • Unary Operators on Boolean Literals:
    • The ! operator can invert boolean literals directly.
    • Example: System.out.println(!true); // Output: false
  • Usage with Arrays:
    • Increment and decrement operators can modify array elements directly.
    • Example:
      int[] arr = {1, 2, 3};
      arr[0]++;
      System.out.println(arr[0]); // Output: 2
  • Chained Logical NOT:
    • Multiple ! operators can be chained, effectively toggling the boolean value multiple times.
    • Example:
      boolean flag = true;
      System.out.println(!!!flag); // Output: false