assign int to byte vs double to float in java

后端 未结 3 2006
粉色の甜心
粉色の甜心 2020-12-16 07:15

1.when we assign double to float variable compiler gives us error

float f = 2753.2211;

possible loss of precision<

相关标签:
3条回答
  • 2020-12-16 08:01

    The second case is explicitly allowed by the JLS as a special case. In JLS 5.2, which deals with narrowing conversions, it says:

    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.

    ...

    In other words, for the non-long integer-like values, you can implicitly narrow them iff the value you're narrowing is a constant that fits within the type you're specifying.

    I'm guessing the same trick isn't applied to floats because floating point values are trickier than integer values. For instance, 0.1 can't be exactly expressed in a floating point, while 1.0 can. That means that double d = 0.1 isn't actually putting the value 0.1 into d -- just a value that's very close to 0.1. Given that, the "does it fit exactly" rule doesn't apply even to floating point literals, and the question of "does it fit exactly when we narrow" becomes trickier. Your options would basically be:

    • always allow it (which could cause some surprising behavior if a value is significantly different than its literal representation)
    • only allow it if the value can be exactly put in. This would look highly inconsistent:
      • float f1 = 1.0 and double d1 = 1.0 both work
      • double d2 = 0.1 works, but float f2 = 0.1 doesn't -- confusing!
    • never allow it (slightly inconvenient, because you have to type the f char in the literal)

    Given these options, it seems that the designers of the JLS chose the least of three not-great options.

    0 讨论(0)
  • 2020-12-16 08:05

    int is a 32-bit signed integer, byte is an 8-bit signed integer. A byte runs from -128 to 127, while a int runs from -2147483648 to 2147483647

    Precision isn't lost, but do not cast a big int into a small byte or you will lose data.

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

    Data isn't going to be lost in the second case.

    A byte comprises the values of -128 and 127 inclusive, so as long as your int fits within that range, no loss of precision can occur.

    Your second value is not a float-literal; by default, all floating point values in Java are double. You can explicitly make that a float by adding f to the end of it.

    float f = 2573.2211f;
    
    0 讨论(0)
提交回复
热议问题