Por que byte e divisão curta resulta em int em Java?
Em Java, se dividirmosbyte
sshort
s ouint
s, sempre temos umint
. Se um dos operandos forlong
, nós conseguiremoslong
.
Minha pergunta é - por quebyte
oushort
divisão não resultar embyte
oushort
? Por que sempreint
?
Aparentemente, não estou procurando a resposta "porque o JLS diz isso", estou perguntando sobre a lógica técnica dessa decisão de design na linguagem Java.
Considere este exemplo de código:
byte byteA = 127;
byte byteB = -128;
short shortA = 32767;
short shortB = -32768;
int intA = 2147483647;
int intB = - -2147483648;
long longA = 9223372036854775807L;
long longB = -9223372036854775808L;
int byteAByteB = byteA/byteB;
int byteAShortB = byteA/shortB;
int byteAIntB = byteA/intB;
long byteALongB = byteA/longB;
int shortAByteB = shortA/byteB;
int shortAShortB = shortA/shortB;
int shortAIntB = shortA/intB;
long shortALongB = shortA/longB;
int intAByteB = intA/byteB;
int intAShortB = intA/shortB;
int intAIntB = intA/intB;
long intALongB = intA/longB;
long longAByteB = longA/byteB;
long longAShortB = longA/shortB;
long longAIntB = longA/intB;
long longALongB = longA/longB;
byteA
dividido porbyteB
não pode ser nada além de um byte, pode?
Então, por que devebyteAByteB
feijãoint
? Por que nãoshortALongB
estarshort
?
PorqueintALongB
tem que serlong
, o resultado sempre será adequadoint
, não vai?
Atualizar
Como @Eran apontou,(byte)-128/(byte)-1
resulta em128
que não se encaixabyte
. Mas porque nãoshort
então?
Atualização 2
Em seguida, como @Eran apontou (novamente),(int) -2147483648 / (int) -1
também não cabeint
mas o resultado é, no entantoint
, nãolong
.