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

bit-manipulation, java

Solution

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.

Problem

``` 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 ```

Original source