Consider the following code snippet:
class TypeCast{
public static void main(String[] args){
byte by = 4; //compiler casts int literal to byte
doCasting(4); //Compilation Error: external type casting is required. WHY ?
}
public static void doCasting(byte by){
}
}
I think above code snippet is quite self-explanatory. While int
literal assignment to byte
type, compiler does the required cast automatically. Same thing does not happen when we call a method taking byte
parameter with int literal. Why?
This is the difference between an assignment context (JLS 5.2) and an invocation context (JLS 5.3) for conversions.
Assignment context conversions include:
In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:
- 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.
That isn't present in the invocation context conversions.
It's not clear to me why the language was designed that way, other than to possibly simplify overload resolution - if you had:
doCasting(5);
...
doCasting(int x) {}
doCasting(byte b) {}
then you could argue for either of them being the "best match" - byte
is a more specific type than int
, but if you think of the literal as being of type int
, then the byte
overload makes requires a conversion whereas the int
overload doesn't.
By making the byte
overload simply not applicable, the question is removed.
See more on this question at Stackoverflow