0

I was just playing around with some code and was curious about the following result:

byte b = 50;
b *= 50; 
System.out.println(b);

The output I get is -60.

Why is this the case? Also, why don't I get a compile error as this seems to be a form of implicit type conversion (i.e. to an int).

For example, I cannot write the following:

b = b * 50; 
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Yung_Ali
  • 1
  • 1
  • A java byte can hold values from -128 to 127. So of course if you try to put 50*50 into it you will get an overflow and not the correct result. – OH GOD SPIDERS May 31 '22 at 14:19
  • *why don't I get a compile error* -- because if the language defined the result of the calculation of `a op b` in `a op= b` to be widened to `int` for smaller integral types, priot to assignment back into `a`, the `op=` operator would be unusable for those types, and thus not exist in the language. – dangling else Jun 01 '22 at 01:32

0 Answers0