Java Reference
In-Depth Information
Unary Plus Operator (+)
The unary plus operator (+) is used in the form
+operand
The operand must be a primitive numeric type. If the operand is of the byte , short , or char type , the unary
plus operator promotes it to int type . Otherwise, there is no effect of using this operator. For example, if there is an
int variable num , which has a value of 5 , +num still has the same value of 5. The following example illustrates its use:
byte b1 = 10;
byte b2 = +5;
b1 = b2; // Ok. byte to byte assignment
// A compile-time error. b2 is of the type byte. But, use of the unary plus operator on
// b2 promoted its type to int. Therefore, +b2 is of the type int.
// int (+b2) to byte (b1) assignment is not allowed.
b1 = +b2;
b1 = (byte) +b2; // Ok
Unary Minus Operator (-)
The unary minus operator (-) is used in the form
-operand
The unary minus operator arithmetically 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
// A compile-time error. b2 is of the type byte. But, use of unary minus operator (-) on
// b2 promoted its type to int. Therefore, -b2 is of type int.
// int (-b2) to byte (b1) assignment is not allowed.
b1 = -b2;
b1 = (byte) -b2; // Ok
 
Search WWH ::




Custom Search