my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why won't Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why won Watch "why won New topic

why won't "float x = 1.0;" compile

Bill Nelsen

Joined: Aug 11, 2004
Posts: 27
I understand that

float x = 1.0; // generates a compile error


double x = 1.0; // compiles

But does anyone understand the reasoning behind this. Why isn't 1.0 considered to be an acceptable value for float types??

Nitin Bhagwat
Ranch Hand

Joined: Sep 09, 2004
Posts: 132
Default type of values having decimal point is double. So, 1.0 is double and not float.

"Imagination is more important than knowledge. Knowledge is limited. Imagination encircles the world."
Vipin Das
Ranch Hand

Joined: Jul 05, 2004
Posts: 47
The compiler takes floating point literals as Double by default. That is why it shows an error. We can specify it as a float by adding 'f'.
like float x = 1.0f; Here we tell the compiler that this is a float, so dont take as a double.
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
However "float x = 1;" using an integer literal compiles OK.

javac is concerned that converting a double value to a float value will lose precision.

You would need either "float x = 1.f;" or "float x = (float)1.;

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: why won't "float x = 1.0;" compile
It's not a secret anymore!