Reputation: 3349
How 19.5 is a double value. Why we need to append F
to it to make it float
? Just want to know how we identify a number whether it is float
or double
.
Upvotes: 1
Views: 2778
Reputation: 9117
19.5
is a floating-point literal in java. Quote from Java Language Specification #3.10.2:
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.
Now when we know that 19.5
is of type double, let's look at your example in the comments:
float value = 19.5;
Conversion from double
to float
in java is a narrowing primitive conversion. This type of conversion should be explicit. That's why you need to use floating-point literal of type float
to get rid of the conversion
float value = 19.5f;
or to make this conversion explicit
float value = (float) 19.5;
Upvotes: 10
Reputation: 1582
For handling downcasts, or narrowing conversions. Whenever you downcast a long to an int, or a double to a float, the possibility for data loss exists. So, the compiler will force you to indicate that you really want to perform the narrowing conversion, by signaling a compile error for something like this:
float f = 19.5;
Because 19.5 represents a double, you have to explicitly cast it to a float (basically signing off on the narrowing conversion). Otherwise, you could indicate that the number is really a float, by using the correct suffix;
float f = 19.5f;
by default 19.5 is double literal, So to tell compiler to treat it as float explicitly -> it uses f or F
Upvotes: 1