Anybody has idea why compiler can't cast value '7' in 'short'? explicit casting is working but while passing parameter it is not working!!!
class Alien {
String invade(short ships) { return "a few"; }
String invade(short... ships) { return "many"; }
}
public class Wind {
public static void main(String [] args) {
short temp = 7;
System.out.println(new Alien().invade(7));
}
}
Integer literals (which is what we're talking about here) are int
values unless they have a suffix to indicate that they're long
values instead.
From section 3.10.1 of the specification:
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
But casting is fine. It's also entirely possible to have a constant which isn't a literal. For example:
public static final short THIS_IS_A_SHORT = 7;
Here THIS_IS_A_SHORT
is a constant of type short
. And in this case you don't even need a cast, because it's an assignment. Assignments are subject to JLS section 5.2, which includes:
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.
A method argument is not subject to assignment conversions.