Why is it so that both float and int requires 4 bytes of memory storage, but int can be converted to float and float cannot to int? Please explain in terms of memory storage, like what happens in the memory storage?
class A5 {
public static void main(String[] args) {
float f = 10.5f;
int a = f;
System.out.println(a);
}
it gave error like this->
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from float to int
Syntax error, insert "}" to complete ClassBody
at A5.main(A5.java:6)
A conversion from
floattointis lossy both in precision, but also in range (magnitude).On the precision side, storing 10.5f in an
intwould make you lose the fractional value, but the range is probably even more relevant. Anintcan store [-2147483648, 2147483647], while afloatcan store numbers roughly in the range [-3.4e38, 3.4e38]. In other words,floathas a lot of numbers you cannot just store in anintwithout some form of overflow.So, because you could lose precision and/or have overflow, the Java compiler doesn't allow you to assign a
floatto anintwithout explicitly signalling that you accept the consequences. And you signal that by using an explicit cast (in your example, you would need to useint a = (int) f;).Although
floatandintare both 4 bytes, their representation is entirely different. If you would want to know "what is the equivalentintvalue for the 4 bytes of afloat", you will need to useFloat.floatToIntBits(float), but the integer value you'll receive will have no (seeming) correlation to the original float value (e.g.Float.floatToIntBits(10.5f)produces the integer1093140480).