Why in this line the floating point number is treated as double? I thought float has enough space to hold that number.
float f = (float)333.50;
Why in this line the floating point number is treated as double? I thought float has enough space to hold that number.
float f = (float)333.50;
The value 333.50
can be represented in the float
type but is a double literal. Use 333.50F
to have a float literal.
The specification, see Oracle Java documentation about Primitive Data Types, is clear about the different literals:
Floating-Point Literals
A floating-point literal is of type
float
if it ends with the letterF
orf
; otherwise its type isdouble
and it can optionally end with the letterD
ord
.
There is a similiar case for integer literals but here the smaller type (int
) is the default:
Integer Literals
An integer literal is of type
long
if it ends with the letterL
orl
; otherwise it is of type int. It is recommended that you use the upper case letterL
because the lower case letterl
is hard to distinguish from the digit1
.
Because the Java specification says that by default a floating-point literal is a double
value.
Floating-Point Literals
A floating-point literal is of type
float
if it ends with the letterF
orf
; otherwise its type isdouble
and it can optionally end with the letterD
ord
.
Rather than using a narrowing conversion (double
to float
), just use the F
prefix in the literal declaration :
float f = 333.50F;
333.50
is a literal of type double
. That's simply the rule - it comes from C way back in the 1970s. It's just like 0
is a literal of type int
.
The equivalent float
literal is 333.5f
, or you can use a compile time evaluable constant expression like (float)333.50
.
Indeed 333.5
can be represented exactly as a float
as it's a dyadic rational.
This is how you define literals in java (JLS)
int a = 12;
long b = 12L;
float c = 12.0f;
double d = 12.0d;
so you can write those like;
i = 1222;
is an integer literal
and the same way
j = 3.1415;
is a double literal
of course you can EXPLICITLY define the type:
i = 1222L; //for long values
j = 3.1415f; //for float values
by default floating point literal is double
in java , if you want the value to float you may do this
float f = 333.5f
Java by default treats any decimal point values as the double. so you need to particularly define which type of primitive data type you are using. for example:
`int i=10; // default
long l=123456L;
float f=123.12F;
double d=123.12345; // default
` so you must explicitly define the what type of data type you are using when not using the default types