Java 为什么不能将整型文字作为参数传递给以字节作为形式参数的方法

Java 为什么不能将整型文字作为参数传递给以字节作为形式参数的方法,java,Java,查询1: byte a = 0; // int to byte implicit conversion happens, correct!, no CTE [compile time error] setByte(0); // CTE!, why ? implicit conversion do not happen here void setByte(byte b){} byte b_byte = 128 - 1; // integer literal computation result

查询1:

byte a = 0; // int to byte implicit conversion happens, correct!, no CTE [compile time error]
setByte(0); // CTE!, why ? implicit conversion do not happen here 
void setByte(byte b){}
byte b_byte = 128 - 1; // integer literal computation results to 127 int which implicitly casts to byte and as 127 is in range of byte so no CTE, Correct!
int a_int = 2147483647; // in range of int, so no CTE
int b_int = 2147483648 - 1; // still in range of int but CTE, why ?
查询2:

byte a = 0; // int to byte implicit conversion happens, correct!, no CTE [compile time error]
setByte(0); // CTE!, why ? implicit conversion do not happen here 
void setByte(byte b){}
byte b_byte = 128 - 1; // integer literal computation results to 127 int which implicitly casts to byte and as 127 is in range of byte so no CTE, Correct!
int a_int = 2147483647; // in range of int, so no CTE
int b_int = 2147483648 - 1; // still in range of int but CTE, why ?
请解释,并指向定义这些规则的JLS部分

首先,介绍可以分配的值

此外,如果表达式是
byte
short
char
int
类型的常量表达式(§15.28):

(int) (2147483648L - 1)
  • 如果变量的类型为
    byte
    short
    char
    ,并且常量表达式的值可以用变量的类型表示,则可以使用缩小原语转换
对于
字节a=0
常量表达式是
int
0
,它被缩小为
字节

接下来,介绍可以传递给方法的值

严格调用上下文和松散调用上下文都不包括赋值上下文中允许的整数常量表达式的隐式收缩

因此,在调用上下文(方法调用)中不允许的常量表达式缩小转换中,代码存在编译器错误

您的代码
128-1
是一个常量表达式,其范围缩小到
字节

但是,
2147483648-1
是不允许的,因为
2147483648
本身

如果十进制文字2147483648出现在除一元减号运算符的操作数之外的任何位置,则为编译时错误;或者如果int类型的十进制文本大于2147483648(231)

如果确实要使用不必要的复杂表达式来初始化
int
,可以使用
long
文本使表达式合法:

2147483648L - 1
但是您必须显式地将表达式强制转换为
int
;从
int
int
之间没有隐式缩小:

(int) (2147483648L - 1)
奇怪的是,您不必在表达式周围放置括号,以便强制转换应用于整个表达式,尽管为了清晰起见,我强烈建议使用括号

(int) 2147483648L - 1  // It's 2147483647!

超出
int
范围的
long
文本上的
int
强制转换将产生-2147483648,一个有效的
int
值。这里减去1涉及负方向的溢出,产生2147483647的预期值。

不能将
long
传递给需要
int
的方法,但可以传递需要
long
int
的方法,因为
long
int
宽。所有的下调都是明确的。裸整数被视为
int
s,可以根据需要隐式向上转换为
long
double
。沮丧是不同的。您需要明确说明类型或强制转换。您确定
2147483648
int
@CarlosHeuberger范围内吗?不是,它只是
整数的一个。最大值