0

I am confused about datatype conversion in Java. Why does this code work:

long q = 5;
long r = 4;

int p = 0;
p -= q * r; 

while the code below gives a compile error?

Type mismatch: cannot convert from long to int

long q = 5;
long r = 4;

int p = 0;
p = p - q*r;

How is explicit subtraction handled in Java as opposed to explicit subtration?

Ufder
  • 527
  • 4
  • 20

1 Answers1

-1

p -= q * r succeeds for two reasons:

First, q * r is a compile time constant, and is known to to be within the int range.

Secondly, a += b is not the same as a = a + b, it’s the same as a = a + (int)b.

Combine those two facts and compiler knows what it can do safely.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Two reasons? And you managed to get them both wrong: 1) `q * r` is not a compile time constant, because they are not `final`. --- 2) `a += b` is the same as `a = (int) (a + b)`. not `a = a + (int)b`. --- Besides, the question already have many answers elsewhere, so shouldn't be answered here. – Andreas Aug 01 '21 at 07:34