Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does narrowing work in method invocation in Java?

Tags:

java

narrowing

Why this is giving the compile time error? 2 is constant at compile time, therefore narrowing should be allowed here since 2 is 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: The method sum(int,byte) in the type ForTest is not applicable for the arguements (int,int).

Edit: I think the answer lies here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.3 but I am not getting it :(

like image 554
Vikas Mangal Avatar asked Dec 25 '22 07:12

Vikas Mangal


1 Answers

You have to distinguish between assignment conversion and method invocation conversion.

Narrowing Primitive Conversion

First of all, look at JLS §5.1.3:

22 specific conversions on primitive types are called the narrowing primitive conversions:

  • [...]

  • int to byte, short, or char

[...]

Note, that this only explains the mechanism but not the places where such conversions are allowed or not.

Assignment Conversion

Next, look at JLS §5.2:

[...]

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.

[...]

This clearly describes that in the assignment byte b = 2 the narrowing conversion from type int to type byte is allowed.

Method Invocation Conversion

However, when reading JLS §5.3 you will not read anything about a narrowing conversion. So the compiler is doing a correct job.

like image 81
Seelenvirtuose Avatar answered Dec 28 '22 06:12

Seelenvirtuose