Is there a difference in how I initialize a variable: float f = 100; or float f = 100f?

StackOverflow https://stackoverflow.com/questions/23571421

  •  19-07-2023
  •  | 
  •  

Question

Java.

Is there a difference in a way I initialize a variable:

float f = 100; //implies a cast from integer to float

or

float f = 100f; //simply a float initialization

Can the results be different?

Here I tried to do it with a very big floats, but looks like the loss of precision is the same.

float f1 = (float)2000000000;
float f2 = (float)2000000050;
float f3 = 2000000000f;
float f4 = 2000000050f;
System.out.println(f1 + " " + f2 + " " + (f1==f2) + " " + f3 + " " + f4 + " "+ (f3==f4) );

-> 2.0E9 2.0E9 true 2.0E9 2.0E9 true

Any difference with the doubles?

Was it helpful?

Solution

I think the results will be the same. The JLS rules for interpreting a floating-point literal refer to the valueOf(String s) method of Float and Double types; the rules for a type conversion from integer to float types are given by JLS 5.1.2. Both refer to "IEEE 754 round-to-nearest mode". So I think it's safe to assume the results are the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top