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:
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: