1.when we assign double to float variable compiler gives us error
float f = 2753.2211;
possible loss of precision Required to cast.
2.when we assign int to byte variable compiler don't gives us error
byte b = 24;
OK
In second case data can also be lost.Then why casting explicitly is not necessary.?
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:
float f1 = 1.0
and double d1 = 1.0
both workdouble d2 = 0.1
works, but float f2 = 0.1
doesn't -- confusing!f
char in the literal)Given these options, it seems that the designers of the JLS chose the least of three not-great options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With