Is this a bug in Eclipse?
When declaring a short variable the compiler treats the the integer literal as a short.
// This works
short five = 5;
Yet it does not do the same when passing integer literals as short parameters, instead a compilation error is generated:
// The method aMethod(short) in the type Test is not applicable for
// the arguments (int)
aMethod(5);
It clearly knows when an integer literal is outside the range of a short:
// Type mismatch: cannot convert from int to short
short notShort = 655254
-
class Test {
void aMethod(short shortParameter) {
}
public static void main(String[] args) {
// The method aMethod(short) in the type Test is not applicable for
// the arguments (int)
aMethod(5);
// the integer literal has to be explicity cast to a short
aMethod((short)5);
// Yet here the compiler knows to convert the integer literal to a short
short five = 5;
aMethod(five);
// And knows the range of a short
// Type mismatch: cannot convert from int to short
short notShort = 655254
}
}
Reference: Java Primitive Data Types.
It's because when invoking a method, only primitive widening conversions are authorised, not primitive narrowing conversions (which int -> short is). This is defined in the JLS #5.3:
Method invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
On the other hand, in the case of an assignment, narrowing conversion is allowed, provided that the number is a constant and fits within a short, cf JLS #5.2:
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
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