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
  • 90,369
  • 161
  • 124
  • 175
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*" -> implicit conversion before assignment, see specification [1](https://docs.oracle.com/javase/specs/jls/se18/html/jls-15.html#jls-15.26.2-100): "*A compound assignment expression of the form `E1 op= E2` is equivalent to `E1 = (T) ((E1) op (E2))`, where T is the type of E1, except that E1 is evaluated only once.*" and [2](https://docs.oracle.com/javase/specs/jls/se18/html/jls-15.html#jls-15.26.2-300-D): "*the result of the binary operation is converted to the type of the left-hand variable, and the result of the conversion is stored into the variable.*" – user16320675 May 31 '22 at 14:50
  • *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