What is numeric promotion?

前端 未结 4 405
抹茶落季
抹茶落季 2020-12-11 15:48

Can any one tell what is numeric promotion?

相关标签:
4条回答
  • 2020-12-11 16:10

    Numeric promotion is a conversion of an operand (at least one of the numbers involved) to a common type.

    For example:

    int i = 10;
    double d1 = 2.5;
    double d2 = d1 * i;
    

    In this case, i is promoted to double so the calculation can be performed. In some ways, you can think of this is analogous to boxing, but boxing involves moving from a struct to an object (from the stack to the heap). But, using the analogy does give an idea of the fact the integral value is being made into a floating point to perform the calculation.

    0 讨论(0)
  • 2020-12-11 16:16

    Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

    0 讨论(0)
  • 2020-12-11 16:17

    Numeric Promotion Rules

    1. If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.

    2. If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.

    3. Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.

    4. After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands

    0 讨论(0)
  • 2020-12-11 16:25

    If you look here, you will see the following quote:

    Numeric promotion (§5.6) brings the operands of a numeric operator to a common type so that an operation can be performed.

    They are referencing this section, where they give a variety of examples. The classic example is that of an int times a float. The integer is promoted to a float so that the multiplied result is, therefore, a float.

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