0

Why is java convert byte or short data type to int when adding two number?

byte a = 10;
byte b = 20;
byte c = a + b; // Compile Time Error
byte c = (byte) a + b; //Should do typecasting

10 + 20 = 30 and byte can hold til 127 so why does it convert to int type?

1 Answers1

1

Tl;dr: That's just how Java was designed.

Long version:

JVM bytecode is designed to have opcodes of only one byte. This (in theory) keeps bytecode relatively memory efficient. As a result there are only 256 possible opcodes, which significantly limits the number of supported operations. This limitation means tat Java must choose only the most common operations when allocating opcodes.

Additionaly Java bytecode was designed to be compiled to machine code, and on many machines there is no byte addition instruction, and instead all operation have to be done on 32+ bit integers, so it makes little sense to have a bytecode instruction which would have to be compiled to a sequence of byte to integer conversion, followed by addition, followed by integer to byte conversion.

This limitation of the JVM appears to have trickled down into the Java language design resulting in byte addition actually being integer addition, since that is what is supported in JVMs.

PiRocks
  • 1,708
  • 2
  • 18
  • 29