All integer literals are treated as int in java and floating point literals are treated as double in java. Then why does
byte b =10;
does not give any error but
float f = 10.0;
gives a loss of precision error when in both cases down-casting takes place?
In the case of int
to byte
, there's no real concern about a loss of precision, because both types have the same degree of granularity. You'll get an error if you try to convert a literal with a value outside the range of byte
to byte
. (The error message given in that case is slightly misleading.)
In the case of double
to float
, you can have a constant value which is in the right range, but still lose precision. In your specific case of 10.0, the value can be represented exactly in both float
and double
, but that's not the case in general.
As an example of that, consider this:
float f = (float) 10.1; // Or float f = 10.1f;
double d = 10.1;
System.out.println(f == d); // Prints false
That's because precision is being lost in the conversion from double
tofloat
- neither type can represent 10.1 exactly, but double
gets close to it than float
does. The ==
operator will mean f
is converted back to a double
, with a different value to d
.
See more on this question at Stackoverflow