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
  • 654
  • 4
  • 14

2 Answers2

1

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

YCF_L
  • 49,027
  • 13
  • 75
  • 115
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
  • 127,190
  • 21
  • 146
  • 218