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?
Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user.
Specify a Variable TypeCasting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
Type Conversion example – int x=30; float y; y=x; // y==30.000000. 1. In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler.
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.
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