Operators and Assignments - Unary Operators
- operate on a single operand
- the unary ~ , + and - operators can only be applied to numeric primitive types
- the unary ! (logical complement) can only be applied to a boolean type
- rules of unary numeric promotion apply
Unary ~ Bitwise complement (inversion) (JLS §15.15.5)
- only used with integer values
- inverts the bits ie a 0-bit becomes 1-bit and vice versa
- in all cases ~x equals (-x)-1
byte b0 = 7; // binary: 0000 0111
byte b1 = ~b0; // binary: 1111 1000 ( -8 )
~7 = -7 -1 = -8
~3578 = -3578-1 = -3579
~-1234 = -(-1234)-1 = 1233
Unary ! Logical complement (JLS §15.15.6)
- returns the logical complement of a boolean type
!(false) = true; // complement of 'false' is 'true'
!(true) = false; // complement of 'true' is 'false'
Unary + operator (JLS §15.15.3)
The unary plus (+) operator has no effect on the sign of a value; it is included for symmetry only and to allow the declaration of constants
ie MIN_VALUE = +2.0; (JPL pg 128)
Unary - operator (JLS §15.15.4)
- for integers negation effect is the same as subtraction from zero
- two's complement is used for integers so for all values of x, -x equals (~x)+1
byte b;
b = -5; // result: -5
b = (~5) + 1; // result: -5
- negation of the maximum negative int or long value results in the same number. An overflow occurs but no exception is thrown.
int i;
long l = 0L;
i = -(-2147483648); // result: -2147483648
l = -(-9223372036854775808L) // result: -9223372036854775808;
- for floating-point negation is not the same as subtraction from zero
- the unary (-) operator merely negates the sign of the value
double d = 0D;
d = -(15.63); // result: -15.63
d = -(-15.63); // result: 15.63
Example Code
|