 How to Use the Unary Plus and Minus Operators in Java - dummies

How to Use the Unary Plus and Minus Operators in Java

The unary plus and minus operators let you change the sign of an operand in Java. Note that the actual operator used for these operations is the same as the binary addition and subtraction operators. The compiler figures out whether you mean to use the binary or the unary version of these operators by examining the expression.

The unary minus operator doesn’t necessarily make an operand have a negative value. Instead, it changes whatever sign the operand has to start with. Thus, if the operand starts with a positive value, the unary minus operator changes it to negative. But if the operand starts with a negative value, the unary minus operator makes it positive. The following examples illustrate this point:

int a = 5; // a is 5

int b = -a; // b is -5

int c = -b; // c is +5

Interestingly enough, the unary plus operator doesn’t actually do anything. For example:

int a = -5; // a is -5

int b = +a; // b is -5

a = 5; // a is now 5

int c = +a; // c is 5

Notice that if a starts out positive, +a is also positive. But if a starts out negative, +a is still negative. Thus the unary plus operator has no effect. I guess Java provides the unary plus operator out of a need for balance.

You can also use these operators with more complex expressions, like this:

int a = 3, b = 4, c = 5;

int d = a * -(b + c); // d is -27

Here, b is added to c, giving a result of 9. Then the unary minus operator is applied, giving a result of -9. Finally, -9 is multiplied by a, giving a result of -27.