when i execute the below code, i expected it to get warning "can't convert from long to float" because the float is 32 bits and long is 64 bits in size. But looks like no warning, Could anyone explain me how?
public static void main(String[] args)
{
float a=1;
long b=123;
a=b;
System.out.println(a);
}
The range of float
is much larger than the range of long
... there's an implicit conversion which may lose precision, but not magnitude. The same is true for long
to double
.
From JLS 5.1.2:
A widening primitive conversion from
int
tofloat
, or fromlong
tofloat
, or fromlong
todouble
, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (ยง4.2.4).
See more on this question at Stackoverflow