Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does bitwise AND of two short values result in an int value in Java?

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
like image 986
deamon Avatar asked Feb 17 '10 10:02

deamon


2 Answers

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.
like image 128
David Avatar answered Sep 22 '22 18:09

David


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.

like image 39
Michael Borgwardt Avatar answered Sep 25 '22 18:09

Michael Borgwardt