Java分配查询

Dee*_*Jha 5 java

情况1

byte b = 7; // why don't I need to cast 7 to byte in this case? byte b = (byte)7;
System.out.println(b);
Run Code Online (Sandbox Code Playgroud)

输出: 7

案例2

static void fun(byte b) {
   System.out.println(b);
}

public static void main(String []args) {
   fun(7); // Compiler gives error because a cast is missing here.
}
Run Code Online (Sandbox Code Playgroud)

输出: 编译错误:method fun(byte) is not applicable for the argument (int).

我的问题是:在案例1中,如何从一个7隐式地转换byteint,而在案例2中它强制程序员明确地转换它?

7仍在范围内byte.

请建议.

sst*_*tan 1

诸如此类的数字文字7被视为整数。因此,通常情况下,就像在第二种情况下一样,您需要强制转换byte以将其传递到byte预期的位置。

\n
fun((byte)7); // You are forced to cast here.\n
Run Code Online (Sandbox Code Playgroud)\n

但是,您的第一种情况很特殊,因为您在变量初始化语句中使用此整数文字。在这种情况下,JLS 中有一条规则允许进行隐式转换。

\n
byte b = 7; // special JLS rule applies, the cast is done for you automatically.\n
Run Code Online (Sandbox Code Playgroud)\n

JLS规格

\n
\n

另外,如果表达式是 byte、short、char 或 int 类型的常量表达式 (\xc2\xa715.28):

\n

如果变量的类型是 byte、short 或 char,并且常量表达式的值可以用变量的类型表示,则可以使用缩小基元转换。

\n
\n