When using java bitwise operators (such as bitwise-and "|", bitwise-xor "^") , i have just noticed that *int* is returned, even if the operands are bytes or shorts. For example:
Would anyone please happen to know the reason for this? (Sure, you can cast the result later... but why do they return 'int' in the first place?) I mean, when it comes to arithmetical plus (+) I can understand why byte+byte might yield a result larger than byte range (due to 'carry'). But when it comes to bitwise operators(and/or/xor) between 2 bytes, surely they can never yield anything larger than a byte? Or am I missing something in the spec?
In Java Virtual Machine, unfortunely, arithmetical operation only supports int, long, float, and double type, and bitwise operation only supports int and long type. It is mentioned in Java Language Specification and Java Virtual Machine Specification.
Joined: Nov 13, 2002
Thanks for taking the time to read and reply
My question is: *why* did they decide on this spec?
Is there some clever mathematical justification, which i'm missing?
Or is it just some technical reason (like the fact most hardware was 32 bit, at the time)? Or some smarter technical problems, which I can't think of ?
[Sol Mam-Orn]: like the fact most hardware was 32 bit, at the time
I believe this was it, yes. Many operations require only a single processor instruction for a 4-bit int, and would require additional instructions to downcast the result to a smaller type and remove the excess bits. So they defined the language so that wouldn't be necessary most of the time.