0

Can someone please explain to me the difference between the below two variables.

float a =+ 12;
float a =+ 12f;
Stephen Worrall
  • 47
  • 2
  • 10
  • 6
    http://stackoverflow.com/questions/14102955/java-why-do-you-need-to-specify-a-f-in-a-float-literal – Reimeus Oct 21 '15 at 15:48
  • If you donot put f the compiler will treat it as a double value that is the different between first and second value. – Osama Aftab Oct 21 '15 at 15:53
  • 2
    In this particular case, there is no difference in the results. 12 is exactly representable as either float or double, so there is no rounding either way. – Patricia Shanahan Oct 21 '15 at 15:53
  • 3
    And `12` is anyway neither a `float` nor a `double` literal, but rather an `int` literal. It is converted (without loss of precision) to `float` to obtain the value to be assigned. The result of that conversion is exactly the same value represented by the `float` literal `12f`. – John Bollinger Oct 21 '15 at 15:57
  • 1
    @JohnBollinger You are correct that the number `12` is coerced to `float` without loss of precision, but I'd like to clarify for other readers that the coercion of `int` to `float` does *not* guarantee "no loss of precision", since `int` is 31 bits of precision and `float` is 24 bits of precision. See [JLS](https://docs.oracle.com/javase/specs/jls/se6/html/conversions.html#25214): "Conversion of an `int` or a `long` value to `float`, or of a `long` value to `double`, may result in *loss of precision*" – Andreas Oct 21 '15 at 16:20

0 Answers0