Unary Operators in Java with Example

In the previous tutorial, we have learned about variables, data types, operator precedence, and arithmetic operators in java. In this tutorial, we will learn about unary operators in java.


Unary Operators in Java:

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Example of unary operators in java:


class UnaryDemo {
    public static void main(String[] args) {

        int result = +1;  // unary plus operator
        // result is now 1
        System.out.println("Result is now: " +result);

        result--;  // decrement operator
        // result is now 0
        System.out.println("Result is now: " +result);

        result++;  // increment operator
        // result is now 1
        System.out.println("Result is now: " +result);

        result = -result;  // unary minus operator
        // result is now -1
        System.out.println("Result is now: " +result);

        boolean success = false;
        // false
        System.out.println("The result is: " +success);
        // true
        System.out.println("The result is: " +!success);  //Logical complement operator.
    }
}


Output:

unary operators in java



Increment and Decrement operators in java:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.


Example of increment and decrement operator:


class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++; //post increment
        // prints 4
        System.out.println("The value of post increment is: " +i);
        ++i; // pre increment		   
        // prints 5
        System.out.println("The value of pre increment is: " +i);
        // post decrement, prints 5
        System.out.println("The value of post decrement is: " +i--);
        // pre decrement, prints 3
        System.out.println("The value of pre decrement is: " +--i);
    }
}


Output:


Unary Operator in java


Reference: Java Official Documentation.


You may also like these related posts:

1. What is Java - JDK, JRE, JVM?
2. How to set a path in java?
3. Java Hello World program - java first program.
4. Top 100 java interview question and answer.
5. Java Collection framework complete tutorial.

Unary Operators in Java with Example Unary Operators in Java with Example Reviewed by Prashant Srivastava on December 14, 2019 Rating: 5

No comments:

Powered by Blogger.