wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question about specifying float 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 "question about specifying float" Watch "question about specifying float" New topic
Author

question about specifying float

Bret Waldow
Ranch Hand

Joined: Aug 04, 2000
Posts: 59
I am creating my study guide, leading up to the java programmer exam, and I ran into this:
floatmin_float = -1.40129846432481707e-45f
, max_float = 3.40282346638528860e38f;
compiles just fine.
but this (note - no 'f' at end):
floatmin_float = -1.40129846432481707e-45
, max_float = 3.40282346638528860e38;
provokes this error:
ValidPrimitives.java:22: Incompatible type for double. Explicit cast needed to convert double to float.
float min_float = -1.40129846432481707e-45
^
ValidPrimitives.java:23: Incompatible type for double. Explicit cast needed to convert double to float.
, max_float = 3.40282346638528860e38;
^
I can't find anything about this in my reference books. Can someone enlighten me?
regards,
Bret
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1859
Hi,
Part I
The Java Language Specification 3.10.2 Floating-Point Literals
specifies that
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.
thus the literal 2.3 is by default double and not a float .
to specificy it as float one has to say 2.3f or 2.3F
Part II
A conversion from a double to byte, short, char, int, long, or float is a narrowing conversion where in data is definetly lost. As such one has to tell the compiler that it is "OK " by casting it into a respecive type.
for example float f=1.2f;
if one tries int i=f; //compiler complains
one thus has to cast it like this int i=(int)f;
check out the Java Language Specification for Conversions and Promotions 5.1.3 here
Regds.
Rahul.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: question about specifying float