Java - Unary Minus Operator -

What is Unary Minus Operator?

The unary minus operator (-) is used in the form


The unary minus operator negates the value of its operand.

The operand must be a primitive numeric type.

If the type of the operand is byte, short, or char, it promotes the operand to the int type.

The following example illustrates its use:

byte b1 = 10; 
byte b2 = -5; 
b1 = b2;  // Ok. byte to byte assignment 

In the following code, b2 is of the type byte. unary minus operator - on b2 promotes its type to int. -b2 is of type int. int to byte assignment is not allowed.

byte b1 = 10; 
byte b2 = -5; 

b1 = -b2; // A compile-time error. 

To fix the error, add casting.

b1 = (byte) -b2; // Ok