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: (
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[...]
22 :
[...]
int , char
, , , .
, JLS §5.2:
[...], (§15.28) byte, short, char int:, , char, .[...]
, (§15.28) byte, short, char int:
, byte b = 2 int .
byte b = 2
Invocation Invoice
JLS §5.3 . .
, 2 int, .
- (int a, int b), : test.sum(1, (byte)2)
int a, int b
test.sum(1, (byte)2)
int byte . :
int
byte
sum(1, (byte)2);
:
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, . "
, , .
(§5.1.3) , int byte, short, char. int byte, . :
short
char
test.sum(1, (byte)2);
. , , , "" , 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."
Source: https://habr.com/ru/post/1546098/More articles:The expression of Java Pattern.compile is "/login?(\\?.+)?" - javaChrome uncaught error "Protocols must match" on G + signin - google-chromeForm warning message after jquery update - javascriptWhat is the behavior of the mmap () 'ed pointer after closing the file descriptor without first calling munmap ()? - cLaravel 4 session does not expire after life limit - authenticationImplicit typecasting does not work if an integer value is passed as an argument in java - javaПроблемы с QProcess после fork() и execv() - c++Bigcommerce API Product Problem "Calc_price field cannot be written. Remove it from your request before trying again" - phpfread error "Undefined character termination field" - rfread and backslash column - rAll Articles