Based on the snippet below:
// as primitive
MyClass.primitiveMethod(double val); // method signature
MyClass.primitiveMethod(12); // ok
// as object
MyClass.objectMethod(Double val); // method signature
MyClass.objectMethod(12); // error
MyClass.objectMethod(12d); // ok
MyClass.objectMethod((double)12); //ok
Q1: While both 12d
and (double)12
seem to work, are there any difference between specifying suffix and explicit casting? (behaviour/performance)
Q2: Why MyClass.objectMethod(12)
must be considered an error? While 12 is supposed to be resolved to an Integer object, can't Java be smart enough to know that 12 is also a value Double value and just accept it?
Size: Float is of size 32 bits while double is of size 64 bits. Hence, double can handle much bigger fractional numbers than float. They differ in the allocation of bits for the representation of the number. Both float and double use 1 bit for representing the sign of the number.
float uses 1 bit for sign, 8 bits for the exponent, and 23 bits for mantissa, while double uses 1 bit for a sign, 11 bits for the exponent, and 52 bits for mantissa.
double is more precise than float. So, if a more precise and accurate result is required use double. Another reason to use double is that if the number is not fitting in the range offered by the float then use double. We should use float if we have memory constraint because it occupies half-space than double.
Performance-wise there's not likely to be much difference, and double may actually be faster. If Java is being run on a processor that doesn't have a floating-point unit at all, or supports 32-bit floats but not 64-bit floats, then a float could be faster.
For the first question: I'd expect the conversion to double
to be performed by the compiler, but I wouldn't like to say for sure without checking. I'd use the suffix instead, for clarity. (If I need to check, that means anyone maintaining the code would have to check too... why not just use a literal of the right type to start with?)
12 is resolved to an int
, not an Integer
- and there's no implicit conversion from int
to Double
. Just because there's an implicit conversion from int
to double
and another from double
to Double
doesn't mean there's one straight there.
It could have been included, of course - but it would have meant making the language more complicated for a pretty small level of benefit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With