So my question is why do the basic operators have to return an integer every time? Is this is a quirk specific to java, or is there some importance for doing it this way?
The reason it happens is that the Java integral arithmetic operators are defined as int op int -> int
(or long op long -> long
).
Why they defined it that way? I'm not sure, but I can think of three possible explanations:
- Efficient implementation across a range of native instruction sets / architectures.
- Consistency with other languages like C and C++. (I'm not an expert on the standards for these languages, but I found the place in the C99 language spec which says this ... section 6.3.1.1 para 2.)
- Mathematical consistency.
IMO, the latter is probably the most significant.
Suppose that there was an overload for +
with signature byte op byte -> byte
. Now we have a situation where +
is no longer associative. Assume that we have byte b1, b2; int i;
then
(b1 + b2) + i
does the first +
using the byte
operator, and then the second +
using the int
operator.
b1 + (b2 + i)
does the second +
using the int
operator, and then the first +
using the int
operator.
Note that if bytewise b1 + b2
overflows, the two different ways of evaluating the compound expression will give different answers.
But automatically widening the operands to int
and doing the operations as int op int -> int
avoids this.