File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Bill Nelsen
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that

float x = 1.0; // generates a compile error

and

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??

Thanks
 
Nitin Bhagwat
Ranch Hand
Posts: 132
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Default type of values having decimal point is double. So, 1.0 is double and not float.
 
Vipin Das
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
-vipin
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic