short permissions = 0755;
short requested = 0700;
short result = permissions & requested;
I get a compiler error:
error possible loss of precision
found : int
required: short
If I'm not totally wrong the result of binary AND is as long as the longest operand. Why is the result an integer?
Would there be a performance hit, if I would cast to short?
(short) permissions & requested
The short answer (hah!) is, binary numeric promotion.
- If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
If I'm not totally wrong the result of binary AND is as long as the longest operand. Why is the result an integer?
Because the Java Language Specification says that the result of non-long integer arithmetic is always an int. It was probably written that way in acknowledgment of the fact that 32 bit CPUs work like that internally anyway - they actually don't have a way to do arithmetic with shorts.
Would there be a performance hit, if I would cast to short?
For the reason given above: no - it will have to happen anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With