This is one of the oddities of Java.
FIrst of all "possible loss of precision" is *NOT* an error; it is just a warning.
You will note that the warning says "found: int, required: byte".
What it is saying is that the expression on the RIGHT side of the equals sign is an integer, but the variable on the left side is only a byte. So, when you assign the integer to the byte, indeed you could "lose precision". And you will, if the integer value is larger than 255.
WHY is the expression on the right side an integer??? When the variable number
is just a byte?? Simply because the constant 2
is, by Java definition, an integer. And any time you do mixed-type arithmetic, the values are "promoted" to the largest precision type. [Actually, with Java it's a tad more complicated than that, but for this example that statement is true enough.]
Now, most of us were always taught that
number *= 2;
is IDENTICAL to
number = number * 2;
And it's true that the numeric result will be the same. But the big difference is that Java *KNOWS* (for some weirdo reason...but you need a real Java afficianado and guru to tell you the gory details) that you are asking for a "byte only" operation. And so no warning message. And you only finally get an error when you really do exceed the capacity of the byte.
Again, there are some esoteric reasons why the behavior here changed between JDK 5 and JDK 6. In some magic way, the version 6 behavior is "more correct."
If you care a lot, I think I could probably find the chapter and verse that explains the change; but honest, for 99.4% of all practical purposes, it doesn't matter.
And if you really really care a lot, then buy this book:
The book explains not only this point but dozens of other tricks and edge cases. And convinces you that language designers must all be just a little crazy. (Having designed a couple in my own time, I can attest that the latter is definitely true.)