0

In Java if I do the following I get an error

byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!

Ok I understood why I got that error . But now if I do b*=2 I don't get any error. Why?

Raj
  • 664
  • 4
  • 16

2 Answers2

1

Because when you make b *= 2; in fact this operation *= will cast your int to byte.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

The reason is simply because there are different rules for narrowing conversions for = and *=.

See here for details on widening in general; and then you go here to understand the difference for those *= operations.

You, see

b *= 2 

works out as

b = (byte) ( (b) * 2 ) 

and that narrowing conversion doesn't play a role here.

GhostCat
  • 137,827
  • 25
  • 176
  • 248