Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type casting vs using suffix for float/double Java - difference?

Tags:

java

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?

like image 667
kctang Avatar asked Jan 04 '12 17:01

kctang


People also ask

What is the difference between Java data types float and double?

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.

In what way is float initialization different from double initialization?

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.

Should I use float or double Java?

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.

Is float faster than double Java?

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.


1 Answers

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.

like image 55
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet