Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 874
MiamiBeach Avatar asked Oct 20 '22 08:10

MiamiBeach


1 Answers

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.

like image 175
ajb Avatar answered Oct 23 '22 10:10

ajb