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

前端 未结 5 1149
孤独总比滥情好
孤独总比滥情好 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.

    0 讨论(0)
  • 2021-01-13 10:34

    Conversion from a number with a smaller range of magnitude ( like int to long or long to float ) is called widening. The goal of widening conversions is to produce no change in the magnitude of the number while preserving as much of the precision as possible. For example, converting the int 2147483647 to float produces 2.14748365e9 or 2,147,483,650. The difference is usually small, but it may be significant.

    Conversely, conversion where there is the possibility of losing information about the magnitude of the number ( like long to int or double to long ) is called narrowing. With narrowing conversions, some information may be lost, but the nearest representation is found whenever possible. For example, converting the float 3.0e19 to long yields -9223372036854775807, a very different number.

    0 讨论(0)
  • Because a literal number has no type.

    Once you give it a type it must be casted to the other one:

    int i = 13;
    byte b = (byte) i;
    
    0 讨论(0)
  • 2021-01-13 10:45

    A byte has 8 bits. An int, 32 bits, and it is a signed number.

    0 讨论(0)
  • 2021-01-13 10:53

    From here:

    Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of an identity conversion (§5.1.1), a widening primitive conversion (§5.1.2), or a widening reference conversion (§5.1.4). In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:

    • The expression is a constant expression of type byte, short, char or int.
    • The type of the variable is byte, short, or char.
    • The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

    In your example all three conditions are satisfied, so the narrowing conversion is allowed.

    P.S. I know the source I'm quoting is old, but this aspect of the language hasn't changed since.

    0 讨论(0)
提交回复
热议问题