Understanding narrowing primitive conversion

后端 未结 1 774
悲&欢浪女
悲&欢浪女 2021-01-24 18:15

I\'m trying to understand the narrowing primitive conversion concept in Java. Here\'s what the JLS 5.1.3 says about it:

22 specific conversions on primiti

相关标签:
1条回答
  • 2021-01-24 18:39

    Since there is the implicit conversion converting long to int

    There isn't. There's an explicit conversion. Narrowing conversions aren't generally applied implicitly, precisely because they can lose information. So you'd need:

    int c = (int) 88L;
    

    Indeed, the initial part of JLS section 5 even gives an example:

    // Casting conversion (5.4) of a float literal to
    // type int. Without the cast operator, this would
    // be a compile-time error, because this is a
    // narrowing conversion (5.1.3):
    int i = (int)12.5f;
    

    There are some cases where narrowing conversions are applied explicitly in assignment contexts (JLS 5.2) though:

    In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

    • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

    • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

      • Byte and the value of the constant expression is representable in the type byte.

      • ... (similar for Short and Character)

    That's why this is valid even though the type of the literal 120 is int:

    byte x = 120;
    

    Compare that with widening conversions, which are permitted within assignment contexts and invocation contexts (JLS 5.3).

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