Why cant we use a short if we are sure the counter wont go behind or above -2^15 or 2^15 - 1? Why is java doing this - when we think we can save some memory?
Vinoth Kumar Kannan wrote:then why do we need short at all? instead of having 4 categories of integers - byte,short,int,long we can have just int and long,right?
does java provide us something(short) not to be used - even if it is used it is actually not being used at all(promoted to int)?
Because sometimes there are situations where it does make a difference. Suppose that you have some data structure that contains millions of numbers, and you know that each number fits in the range of a short. It can be a noticeable difference if you have to store, for example, 10 million numbers - you'll save 20 MB if you store them as shorts.
But a loop counter is only one variable; making it a short instead of an int saves 2 bytes of memory, which will absolutely not make any noticeable difference in speed or memory usage at all.