Floating point literals in Java are double by default.
A floating-point literal is of type float if it is a suffix with the letter ASCII F or F ; otherwise, its type is double , and it can optionally be a suffix with the letter ASCII D or D
You cannot assign a double value to float without explicitly narrowing the conversion. Therefore, you have two options:
- For literals, use the suffix
F or F to denote a float value. - For non-literals, use explicit listing
(float)
An example of the latter:
double d = 1.1; float f = (float) d;
About increasing conversions
The reason this compiles:
float f = 1;
It means that the conversion extension from int to float can be done implicitly in the destination context.
Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow you to use one of the following:
- extension of primitive conversion (Β§5.1.2)
- [...]
The following 19 specific transformations for primitive types are called expanding primitive transformations:
int to long , float or double- [...]
Another data type suffix for literals
As mentioned above, there is also a D or D suffix for double . Consider this snippet, for example:
static void f(int i) { System.out.println("(int)"); } static void f(double d) { System.out.println("(double)"); }
There is also a suffix for long literals, which is L or L (lowercase letter). It is highly recommended that you use the uppercase option.
An Integer literal is of type long if it is a suffix with the letter ASCII L or L ( ell ); otherwise, it is of type int . The suffix L is preferred because the letter L ( ell ) is often difficult to distinguish from the number 1 ( one ).
polygenelubricants
source share