How does narrowing work in method invocation in Java? -


why giving compile time error? 2 constant @ compile time, therefore narrowing should allowed here since 2 in range of byte.

public class test {    public static void main(string[] args) {      fortest test=new fortest();     test.sum(1, 2); //compile time error here  }  } class fortest {  public int sum(int a,byte b) {     system.out.println("method byte");     return a+b; } } 

the error is: method sum(int,byte) in type fortest not applicable arguements (int,int).

edit: think answer lies here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.3 not getting :(

you have distinguish between assignment conversion , method invocation conversion.

narrowing primitive conversion

first of all, @ jls §5.1.3:

22 specific conversions on primitive types called narrowing primitive conversions:

  • [...]

  • int byte, short, or char

[...]

note, explains mechanism not places such conversions allowed or not.

assignment conversion

next, @ jls §5.2:

[...]

in addition, if expression constant expression (§15.28) of type byte, short, char, or int:

  • a narrowing primitive conversion may used if type of variable byte, short, or char, , value of constant expression representable in type of variable.

[...]

this describes in assignment byte b = 2 narrowing conversion type int type byte allowed.

method invocation conversion

however, when reading jls §5.3 not read narrowing conversion. compiler doing correct job.


Comments

Popular posts from this blog

qml - Is it possible to implement SystemTrayIcon functionality in Qt Quick application -

sql server - MSSQL Text and Varchar(MAX) fields shown (MEMO) in DBGrid -

double exclamation marks in haskell -