Why does JVM convert addition of short and byte whose outcome is within range of short to an int ?

why not the following code which gives compilation error

Is it because b and s are not final and hence their value can change. So at a later stage, addition of byte and short may yield a large value which will require int for storing.

All whole number values are promoted to int during computation. It's an easy rule to remember and it produces cleaner code. Most computers nowadays don't have 16 bit or 8 bit registers and Java definitely uses 32 bit words for its whole numbers. Otherwise the compiler would have to generate code to mask off the upper bytes on a byte or a short, then check for overflow of byte or short arithmetic. It's not worth the hassle and generates inefficient code. [ September 06, 2005: Message edited by: Rick O'Shay ]

Arnb Sen
Ranch Hand

Joined: Feb 23, 2004
Posts: 145

posted

0

Learnt about Whole Numbers when I was a kid in school How does it relate here ?

Machines can't manage the purely abstract concept of a number. It has to know how to store the number, and it has to know how much space it needs. What makes the most sense at the machine level is binary (or base 2) representation.

At the lowest level of a calculating machine, a byte value of 42 is represented in binary digits as 00101010. That is, you have 8-digits to represent a number, but each column is a power of 2, not a power of 10. Instead of having columns for 1s, 10s, 100s, 1000s, etc., you have 1s, 2s, 4s, 8s, 16s, 32s, 64s, 128s. The only allowed values in each column are 0 and 1. So for 42, the columns with 1 in them are 'on': 32, 8, and 2. The rest are 'off'.

The data type supplied by a programming language defines all this for your convenience. A byte on most computer systems is 8-bits wide. If you turned all the bits on, you'd have the sum of all its columns, or 256. However, for the Java byte, short, int and long types, the leftmost bit expresses positive (0) or negative (1) value. This leads to some other necessary rules: after all, you don't want to call byte value 1000000 "negative zero." There are some other important conventions to know, but I'll leave them out here.

So an 8-bit number can store the range of numbers from -2^7 to (2^7 - 1), or -128 to 127. I guess you could say zero is 'positive,' if you wanted to say this is an even division of positive and negative values.

A short is 16-bits wide, so you can cover from -2^15, or 32768, to 2^15-1, or 32767.

Make visible what, without you, might perhaps never have been seen. - Robert Bresson