A few related questions here.
As per the title, why is it a requirement if we are specifying the variable type as long or float, double? Doesn’t the compiler evaluate the variable’s type at compile time?
Java considers all integral literals as int – is this to lessen the blow of inadvertent memory waste? And all floating-point literals as double – to ensure highest precision?
When you have a constant there are subtle differences between value which look the same, but are not. Additionally, since autoboxing was introduce, you get a very different result as less.
Consider what you get if you multiply 0.1 by 0.1 as a float or as a double and convert to a float.
prints
Now compare what you get if you use either
floatorintto perform a calculation.prints
Compare
intandlongprints
compare
doublewithlongprints
In summary its possible to construct a situation where using
int,long,doubleorfloatwill produce a different result compared with using another type.