Narrowing Type Conversion: Why is assignment of int to a byte in a declaration allowed?

前端 未结 5 1204
孤独总比滥情好
孤独总比滥情好 2021-01-13 10:20

This may sound too trivial for an intermediate Java programmer. But during my process of reviewing Java fundamentals, found a question:

Why is narrowing conversion l

5条回答
  •  情书的邮戳
    2021-01-13 10:28

    Because byte b = 13 ; is assignment of a constant. Its value is known at compile time, so the compiler can/should/will whine if assignment of the constant's value would result in overflow (try byte b = 123456789 ; and see what happens.)

    Once you assign it to a variable, you're assigning the value of an expression, which, while it may well be invariant, the compiler doesn't know that. That expression might result in overflow and so the compiler whines.

提交回复
热议问题