How does narrowing work in a method call in Java?

Why does this give a compile-time error? 2 is constant at compile time, so narrowing should be allowed here, since 2 is in the byte range.

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;
}
}

Error: The sum of the method (int, byte) in the ForTest type is not applicable for the arguments (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 do not get: (

+4
source share
6 answers

You must distinguish between assignment conversion and method call conversion.

Narrowing the primitive transform

First of all, see JLS §5.1.3 :

22 :

  • [...]

  • int , char

[...]

, , , .

, JLS §5.2:

[...]

, (§15.28) byte, short, char int:

  • , , char, .

[...]

, byte b = 2 int .

Invocation Invoice

JLS §5.3 . .

+5

, 2 int, .

- (int a, int b), : test.sum(1, (byte)2)

+3

int byte . :

sum(1, (byte)2); 
+1

:

Java- , , , 2.

" m , m , 1 ≤ ≤ n ei Fi, ei ."

, , , "int" " " "". , 1.

" " JLS.

VikasMangal KisHanarsecHaGajjar , .

.

Java 5.1.3 , .

, 5.2

" , (§15.28) byte, short, char int:

, , char, . "

, , .

+1

(§5.1.3) , int byte, short, char. int byte, . :

test.sum(1, (byte)2);
0

. , , , "" , Java , , .

The converse is what happens when you try to do what you tried here. Java sees a value that can fit as a whole, but in order to treat it as a byte, you need to explicitly specify. This is a bit like saying: "Well, I know what I'm doing, and I understand that there are limitations to casting a number into bytes, but I want you to do it anyway."

0
source

Source: https://habr.com/ru/post/1546098/


All Articles