Short and byte data types don't work in loop

Viewed 41

I can't add two short numbers when they are in a loop, but when they outside loop they adds well. Byte type behaves the same. But with integers everything works well. Why does this happening? Java, version 18.

Here is an example:

short a = 5;
short b = 6;
short c = 0;
int i = 0;
while(i < 10) {
  c = a + b;
  i++;
}

When I trying to compile this, it's give me error: incompatible types, possible lossy conversion from int to short.

This also do not work:

int i = 0;
while(i < 10) {
  short a = 5;
  short b = 6;
  short c = 0;
  c = a + b;
  i++;
}

But if I do this(without loop):

short a = 5;
short b = 6;
short c = 0;
c = a + b;

it works well.

2 Answers

In java, the + operator promotes them to an int. You can cast an int value to short value.

  short a = 5;
  short b = 6;
  short c = 0;
  int i = 0;
  while(i < 10) {
      c = (short) (a + b);
      i++;
  }

The full trace would require four citations to the Java Language Specification, but the short answer is that in your working case, where the variables are never re-assigned ever, the compiler is able to find that a and b are effectively final and is treating them as a constant expression whose value (11) is known to be representable in a variable of size short. This appears to be technically in violation of the spec, which would require that only "real" final variables trigger constant-expression treatment, but correct in executed semantics.

Related