Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit type cast not working for method parameters?

Tags:

java

casting

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?

like image 866
maximus335 Avatar asked Feb 09 '15 08:02

maximus335


People also ask

Who carries out implicit type casting?

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.

Is type casting possible in Python?

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)

What do you mean by type conversion type casting list out all the type conversion function with example?

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.


1 Answers

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.

like image 174
Jon Skeet Avatar answered Oct 24 '22 11:10

Jon Skeet