Unary Operators in Java


Unary Operators can be simply defined as an operator that takes only one operand and does a plain simple job of either incrementing or decrementing the value by one. Added, Unary operators also perform Negating operations for expression, and the value of the boolean can be inverted.

  1. Unary Plus, denoted by "+"
  2. Unary minus, denoted by "-"
  3. Unary Increment Operator, denoted by "++"
  • Post-Increment: Value is first processed then incremented. In post increment, whatever the value is, it is first used for computing purpose, and after that, the value is incremented by one.
  • li
  • Pre-Increment: On the contrary, Pre-increment does the increment first, then the computing operations are executed on the incremented value.
  • Post-Decrement: While using the decrement operator in post form, the value is first used then updated.
  • Pre-Decrement: With prefix form, the value is first decremented and then used for any computing operations.

This Java program demonstrates the usage of unary operators (++ and --) in Java. In this program, we first declare an integer variable a and assign it the value of 10. We then print the value of a using System.out.println() method. Next, we use the post-increment operator (a++) to increment the value of a by 1 after it is used in the statement. We then print the value of a again, which is 10 because the post-increment operator returns the value of a before incrementing it.

We then print the value of a again, which is now 11 because the value of a was incremented by the post-increment operator in the previous statement. Finally, we use the pre-increment operator (++a) to increment the value of a by 1 before it is used in the statement. We print the value of a again, which is now 12 because the pre-increment operator increments the value of a before it is used in the statement.

Source Code

public class Unary {
    public static void main(String args[])
    {
        //Unary Operators in Java ++ --
        int a=10;
        System.out.println(a);
        //a++; //a=a+1
        System.out.println(a++);
        System.out.println(a);
        System.out.println(++a);
 
 
    }
}
 

Output

10
10
11
12
To download raw file Click Here

Basic Programs