With the following code:
Float a = 1.2;
there is an error because it takes the decimal as double value and double
is a bigger datatype than float
.
Now, it takes integer as default int
type. So, why is the following code not giving any error?
Byte b = 20;
The compiler is smart enough to figure out that the bit representation of 20 (an int
value) can fit into a byte
with no loss of data. From the Java Language Specification §5.1.3:
A narrowing primitive conversion from
double
tofloat
is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in afloat
zero from a nonzerodouble
and afloat
infinity from a finite double. Adouble
NaN is converted to afloat
NaN and adouble
infinity is converted to the same-signedfloat
infinity.A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.
See also this thread.
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