Reputation: 4511
Is there any difference - in Java - between defining float variables like, e.g., this: 1
and this: 1f
? Is the JVM doing any casts at run-time when I write 1
, or something that could slow down my app?
Regards
Upvotes: 2
Views: 28106
Reputation: 11861
float a = 1;
float b = 1f;
It's the same, but if you do something like:
int a = 1f
Will throw "Type mismatch: cannot convert from float to int"
int b = 1d or 1.0
Will throw "Type mismatch: cannot convert from double to int"
float c = 1d or 1.0
Will throw "Type mismatch: cannot convert from double to float"
Note that:
double a = 2.0;
double b = 2d;
double c = 2.0f;
if (a == b) {
if (c == a) {
if (c == b) {
return 1;
}
}
}
Will return 1;
Regards.
Upvotes: 4
Reputation: 5380
Yes, there is a big difference between 1
and 1f
. As you can't declare a variable without giving its type in java, Its clear 1
is an int
and 1f
denotes float
at compile time itself. This is nothing related to run time or slow down your app.
Upvotes: 1
Reputation: 12326
Java code
float f1 = 1;
float f2 = 1f;
compiles to following bytecode:
0: fconst_1
1: fstore_1
2: fconst_1
3: fstore_2
As you can see, there's no difference at run-time.
Upvotes: 4
Reputation: 3456
If the case like this the JVM will pass it.
public class Test {
public static void main(String[] args) {
float f = 1;
System.out.println(f);
}
}
But it will occur exception if you do something like this:
public class Test {
public static void main(String[] args) {
float f = 1.5;
}
}
Exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - possible loss of precision
required: float
found: double
at package.Test.main(Test.java:17)
What we can analyze for this two example is, for the first example it automatically converted to float
, but for the second example if you add some decimal point without the f
or F
suffix than it will automatically converted to double
.
Upvotes: 2
Reputation: 1145
Basically 1
will default to an int
. If you write 1f
it will be considered a float
. If you write 1.0
(no f) it will default to a double
.
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.
For more info about java data types.
Upvotes: 4
Reputation: 240900
1 is implicitly considered as int
literal where 1f
is considered as float
literal
See
Upvotes: 6