Unary Operators in java 7

In this section you will learn about the Unary operators. This is one type of operators.

Unary Operators in java 7

Unary Operators in java 7

In this section you will learn about the Unary operators. This is one type of operators.

Unary Operators :

The unary operator works with only one operand. Increment/decrement of value negative/positive expression or inverting the value of a boolean comes under the unary operator.

Suppose X is an variable.

+ (Unary plus operator) This operator shows positive value by default numbers are positive. (+X)

- (Unary minus operator) This negative operator change the expression value negative.(-X)

++ (Increment operator) This operator increments the value by 1. (++X / X++)

-- (Decrement operator) This operator decrements the value by 1. (--X / X--)

! (Logical complement operator) This operator inverts the value of a boolean. (!X)

~ (bitwise complement operator) This inverts the bits of a binary number.(~X)

Increment and decrement operators can be used before the operand(prefix) as well as after the operand (postfix). In prefix expression the value is returned after the operation is performed and in postfix expression returns the value before the operation is performed.

Example :

In this example we are using unary operator with variable x.

package operator;

class UnaryOperator {
	public static void main(String[] args) {
		int x = 10;
		int y, z;
		System.out.println("Value of x = " + x);

		y = -x; // Unary minus operator
		System.out.println("Unary minus operator, y = " + y);

		z = +x; // Unary plus operator
		System.out.println("Unary plus operator, z = " + z);

		x++; // Increment operator
		System.out.println("Increment operator, x = " + x);

		x--;// Decrement operator
		System.out.println("Decrement operator, x = " + x);
	}
}

Output :

Value of x = 10
Unary minus operator, y = -10
Unary plus operator, z = 10
Increment operator, x = 11
Decrement operator, x = 10