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?
For the first question: I’d expect the conversion to
doubleto 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 anInteger– and there’s no implicit conversion frominttoDouble. Just because there’s an implicit conversion frominttodoubleand another fromdoubletoDoubledoesn’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.